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.
如果有n个数,它排列的全部可能性是n!。所以看给出的k是多大了,看看可能性。k = a1 X n1! + a2 X n2! +... ai X ni!
class Solution {
public:
string getPermutation(int n, int k) {
string result;
vector<int> base;
vector<int> digits;
for(int ii = 0; ii < n; ii ++) {
if(ii == 0) {
base.push_back(1);
}
else {
base.push_back(ii * base[ii - 1]);
}
digits.push_back(ii + 1);
}
for(int ii = n - 1; ii >= 0; ii --) {
int pos = (k - 1) / base[ii];
k = k - pos * base[ii];
result.push_back('0' + digits[pos]);
digits.erase(digits.begin() + pos);
}
return result;
}
};