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”

  • 确定第 ii 位(0in10\le i\le n-1)时,其后面可能有的情况数是 (ni1)!(n-i-1)!
  • 比如确定第 00 位时,后面可能的情况数是 (n1)!(n-1)!,该位应该取排序中的第 (k1)/(n1)!(k-1)/(n-1)! 个数
  • 然后将该数放到第 00 位,原来的数依次后移
  • 此时就变成了 n1n-1 位的排列
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;
    }
};
posted @ 2020-08-12 10:03  winechord  阅读(76)  评论(0编辑  收藏  举报