Problem:
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.
Analysis:
Solutions:
C++:
string getPermutation(int n, int k) {
string rStr = "";
if(n == 0 || k == 0)
return rStr;
if(n == 1)
return "1";
unsigned int num_of_perm = 1;
for(int i = 1; i < n; ++i)
num_of_perm *= i;
vector<char> candidates;
for(int i = 1; i <= n; ++i) {
candidates.push_back(i + '0');
}
for(int i = 1; i < n && k != 0; ++i) {
cout << "size = " << candidates.size() << ", k = " << k << endl;
unsigned int group_num = (k - 1) / num_of_perm;
rStr.push_back(candidates[group_num]);
candidates.erase(candidates.begin() + group_num);
k = k % num_of_perm;
if(k == 0) {
for(int j = candidates.size() - 1; j >= 0; --j)
rStr.push_back(candidates[j]);
candidates.clear();
break;
}
num_of_perm /= n - i;
}
return rStr;
}
Java
:
Python: