Permutation Sequence
The set [1,2,3,…,n]
contains a total of n! unique permutations.
By listing and labeling all of the permutations in order,
We get the following sequence (ie, for n = 3):
"123"
"132"
"213"
"231"
"312"
"321"
Given n and k, return the kth permutation sequence.
Note: Given n will be between 1 and 9 inclusive.
class Solution {
public:
//没看懂 下次
//(k-1)/(i-1)! (k-1)/(i-1)! 来计算第i位应该用什么数字
//n=3 k=5 4/2=2 3 2*(3-1)!=4 5-4=1
string getPermutation(int n, int k) {
string result;
vector<int> factorials;
vector<int> elements;
for(int i = 0; i < n; i++) {
if(!i) {
factorials.push_back(1);
}
else {
factorials.push_back(i * factorials[i - 1]);
}
elements.push_back(i + 1);
}
int position = 0;
for(int i = n - 1; i > -1; i--) {
position = (k - 1) / factorials[i];
k = k - position * factorials[i];
result.push_back('0' + elements[position]);
elements.erase(elements.begin() + position);
}
return result;
}
};