题目要求:
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个。这样时间复杂度会很高.
仔细想一下可以找到一下规律:
n个数的的第k个排列为:
a1, a2, a3,...an;
接下来我们一个一个数的选取,如何确定第一个数应该是哪一个呢?选取第一个数后剩下全排列的个数为(n-1)! 所以选取的第一个数应该为第
K1 = k;
a1 = K1/(n-1)!位数字
同理当选完a1后只剩下n-1个数字,在确定第二个数应该选择哪个.
a2 = K2 / (n-2)!
K2 = K1 % (n-1)!
........
a(n-1) = K(n-1) / 1!
K(n-1) = k(n-2) % 2!
an = K(n-1)
代码:
class Solution {
public:
string getPermutation(int n, int k) {
vector<int> num(n, 0);
int perm_sum = 1;
for(size_t i = 0; i < n; ++i)
{
num[i] = i + 1;
perm_sum *= (i + 1);
}
string ret;
//因为数组是从0到n-1的 所以基数从 0到k-1
--k;
for(size_t i = 0; i < n; ++i)
{
perm_sum = perm_sum / (n - i);
int selected = k / perm_sum;
ret.push_back(num[selected] + '0');
//选择一个数后重新构造剩下的数组
for(size_t j = selected; j < n - i - 1; ++j)
num[j] = num[j + 1];
k = k % perm_sum;
}
return ret;
}
};