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.
Subscribe to see which companies asked this question
class Solution {
private:
unsigned int hashTable[9];
unsigned int getPai(int n) {
if (n == 0)
return 1;
if (hashTable[n] != 0)
return hashTable[n];
if (n==1)
{
hashTable[1] = 1;
return 1;
}
unsigned int ret = n*getPai(n-1);
hashTable[n] = ret;
return ret;
}
string getPermutationHelper(vector<char> &model, int k) {
int n = model.size();
if (n == 0)
return "";
int numIdx = (k-1) / getPai(n-1); // (k-1) 这里很关键
int remain = k - numIdx*getPai(n-1); // remain = k-numIdx*getPai(n-1)也很关键
char targetChar = model[numIdx];
vector<char> next;
for (int i=0; i<model.size(); i++)
{
if (i != numIdx)
next.push_back(model[i]);
}
return model[numIdx] + getPermutationHelper(next, remain);
}
public:
string getPermutation(int n, int k) {
vector<char> model(n);
for (int i=1; i<=n; i++)
{
model[i-1] = i+'0';
}
return getPermutationHelper(model, k);
}
};