Leetcode--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.

思路

假设集合为[1,2,3,4],求出第6个组合。
第6个组合对应的下标为5(下标从0开始),我们首先求出5所对应的lehmer码(lehmer code的解释参考链接1):
5/3! = 0 余5
5/2! = 2 余1
1/1! = 1 余0
0 (lehmer code最后一位总为0)
所以所求lehmer码为0210

当前集合对应的序列为1234
接下来将lehmer码中的每个数字当做当前序列的下标,下标0对应的集合元素为1,当前序列变成234;下标2对应的集合元素为4,当前序列变成23;下标1对应的集合元素为3,当前序列变成2;下标0对应的元素为2
所以所求的组合即为1432

代码

class Solution {
public:
    string getPermutation(int n, int k) {
        vector<int> jc; ///阶乘表
        list<int> li;   ///序列 1234
        jc.push_back(1);
        int i=1;
        for(; i<n; i++) {
            jc.push_back(jc[i-1]*i);
            li.push_back(i);
        }
        li.push_back(i);

        --k;
        string res="";
        list<int>::iterator it;
        for(int i=n-1; i>0; i--) {
            int index = k/jc[i];
            it = li.begin();
            for(int j=0; j<index; j++) it++;
            res += to_string(*it);
            li.erase(it);
            k = k % jc[i];
        }
        res += to_string(*li.begin());
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值