60. 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 (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个排列,从小到大的顺序
集合序列为 1,2,3,..,n  所有排序的数量为 n!
集合序列为 2,3,...,n 所有排序的数量为 (n-1)!
1234...n 到 1n(n-1)...321之间有 (n-1)!个序列
从最小的组合开始,k/(n-1)! 的值即为左边第一位数,
左边第二位数 为除掉第一位数剩余数值的第 (k%(n-1)!)/k 大的数字
以此类推
*/

class Solution {
public:
    string getPermutation(int n, int k) {
        vector<int>  factorial(n+1,1); //阶乘值
        string res = "";
        deque<int> d(n);  //存储每一位数字 1 2 3 4 ...

        for(int i=1;i<=n;i++){
            factorial[i]=factorial[i-1]*i;
            d[i-1] = i;
        }
        k--;
        for(int i=1;i<=n;i++){
            int index = k/factorial[n-i];  //计算第i位的值
            res += d[index]+'0';
            d.erase(d.begin()+index); //去除使用过的数字
            k-=index*factorial[n-i];
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值