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:
string getPermutation(int n, int k) {
string res;
vector<int>pow(n + 1);
vector<int>num(n);
pow[0] = 1;
for(int i = 1;i <= n;i ++){
pow[i] = i * pow[i - 1];
num[i - 1] = i;
}
while(k > 0 && num.size() > 0){
int idx = (k - 1)/pow[n - 1];//用k - 1!!!
res += char(num[idx] + '0');
num.erase(num.begin() + idx);
k = k - idx * pow[n - 1];
n --;
}
return res;
}
};