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.
这道题太费力气了,还是证明要直接在纸上画个例子,然后模拟,光想可能很多东西很难想到
对于n=4,k=14的情况
1*3! < k
枚举直到 j * 3! >= k
然后取从1开始第j个还没使用过的数,加到结果中,修正k,然后做下一个数
1*2! < k
class Solution {
public:
string getPermutation(int n, int k) {
int factorial[10];
bool used[10];
factorial[0] = 1;
//memset( factorial, 1, sizeof(factorial));不可以用memset,memset按字节赋值,int4个字节,每个字节赋值为1,就是0x01010101了
memset( used, 0, sizeof(used));
for( int i = 1; i <= n; ++i)
factorial[i] = factorial[i-1] * i;
string res = "";
for( int i = n; i >= 1; --i){
for( int j = 1; j <= n; ++j){
if( j * factorial[i-1] < k)
continue;
else{
int m = j;
int p = 1;
for( ; m; ++p){//从下往上数第m个没用过的数字
if( !used[p])
--m;
}
--p;
res += p + '0';
k = k - ((j-1) * factorial[i-1]);//修正k
used[p] = true;//用过了数组就标记为用过
break;
}
}
}
return res;
}
};