/*
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.
寻找第k个排列,从小到大的顺序
集合序列为 1,2,3,..,n 所有排序的数量为 n!
集合序列为 2,3,...,n 所有排序的数量为 (n-1)!
1234...n 到 1n(n-1)...321之间有 (n-1)!个序列
从最小的组合开始,k/(n-1)! 的值即为左边第一位数,
左边第二位数 为除掉第一位数剩余数值的第 (k%(n-1)!)/k 大的数字
以此类推
*/
class Solution {
public:
string getPermutation(int n, int k) {
vector<int> factorial(n+1,1); //阶乘值
string res = "";
deque<int> d(n); //存储每一位数字 1 2 3 4 ...
for(int i=1;i<=n;i++){
factorial[i]=factorial[i-1]*i;
d[i-1] = i;
}
k--;
for(int i=1;i<=n;i++){
int index = k/factorial[n-i]; //计算第i位的值
res += d[index]+'0';
d.erase(d.begin()+index); //去除使用过的数字
k-=index*factorial[n-i];
}
return res;
}
};