leetcode/60. Permutation Sequence

使用逆康托展开打阶乘表快速求解

逆康拖展开是从自然数到序列的映射


例如:

在(1,2,3,4,5)  给出61可以算出起排列组合为34152
具体过程如下:
用 61 / 4! = 2余13,说明  ,说明比首位小的数有2个,所以首位为3。
用 13 / 3! = 2余1,说明  ,说明在第二位之后小于第二位的数有2个,所以第二位为4。
用 1 / 2! = 0余1,说明  ,说明在第三位之后没有小于第三位的数,所以第三位为1。
用 1 / 1! = 1余0,说明  ,说明在第二位之后小于第四位的数有1个,所以第四位为5。

代码:

class Solution {
public:
    string getPermutation(int n, int k) {
        static const int fac[] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
        string num = "123456789";
        string res = "";
        k--;
        for(int i = n;i>0;i--){
            int j = k/fac[i-1];
            k = k%fac[i-1];
            res+=num[j];
            num.erase(j,1);
        }
        return res;
    }
};


 

原文地址:https://www.cnblogs.com/AaronChang/p/12129655.html