leetcode 60. Permutation Sequence (n 位数的第 k 个排列)
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:
“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.
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”
- 确定第 位()时,其后面可能有的情况数是
- 比如确定第 位时,后面可能的情况数是 ,该位应该取排序中的第 个数
- 然后将该数放到第 位,原来的数依次后移
- 此时就变成了 位的排列
class Solution {
public:
string getPermutation(int n, int k) {
string s(n, '0');
int f=1;
for(int i=1;i<=n;i++){
s[i-1]+=i; // "1234...n"
f*=i; // n!
}
k--;
for(int i=0;i<n;i++){
f/=(n-i); // (n-1)!
int j=i+k/f; // (k-1)/(n-1)!
char c=s[j];
while(j>i){
s[j]=s[j-1];
j--;
}
s[i]=c;
k%=f;
}
return s;
}
};