地址:https://leetcode.com/problems/permutation-sequence/
题目:
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 for
n
=
3
n = 3
n=3:
123
132
213
231
312
321
Given n n n and k k k, return the k t h k^{th} kth permutation sequence.
Note:
- Given n will be between 1 and 9 inclusive.
- Given k will be between 1 and n! inclusive.
Example 1:
Input: n = 3, k = 3
Output: “213”
Example 2:
Input: n = 4, k = 9
Output: “2314”
理解:
需要求一个全排列的第k个。
注意全排列的顺序是符合字典序的。
根据k,和n-1个元素的全排列的个数,我们可以确定第位的数字是什么。
比如上面的123
,如果k是3,则可以得到第一位是2
然后找13
这个组合的全排列里的第一个,就是13
了。
实现:
class Solution {
public:
string getPermutation(int n, int k) {
vector<int> fac(n,1);
for (int i = 1; i < n; ++i) {
fac[i] = i*fac[i - 1];
}
string res(n, '0');
for (int i = 0; i < n; ++i)
res[i] += i + 1;
--k;
for (int i = 0; i < n; ++i) {
int index = i + k / fac[n - 1 - i];
char c = res[index];
for (; index > i; --index)
res[index] = res[index - 1];
res[i] = c;
k %= fac[n - 1 - i];
}
return res;
}
};