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.
cantor展开
直接用cantor展开就可以了。
关于cantor展开,请参考:http://www.cnblogs.com/aiterator/p/6675416.html
class Solution
{
public:
string getPermutation(int n, int k)
{
k --;
int res = 1;
list<int> lst;
for(int i=1; i<=n; ++ i)
{
lst.push_back(i);
res *= i;
}
string str;
while(n)
{
res /= n --;
int t = k / res;
auto it = lst.begin();
while(t --)
it ++;
str += *it + '0';
lst.erase(it);
k %= res;
}
return str;
}
};