leetcode: Permutation Sequence

140 篇文章 0 订阅

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):

  1. "123"
  2. "132"
  3. "213"
  4. "231"
  5. "312"
  6. "321"

Given n and k, return the kth permutation sequence.


这道题太费力气了,还是证明要直接在纸上画个例子,然后模拟,光想可能很多东西很难想到

对于n=4,k=14的情况

1*3! < k

枚举直到 j * 3! >= k

然后取从1开始第j个还没使用过的数,加到结果中,修正k,然后做下一个数

1*2! < k

class Solution {
public:
    string getPermutation(int n, int k) {
        int factorial[10];
        bool used[10];
        factorial[0] = 1;
        //memset( factorial, 1, sizeof(factorial));不可以用memset,memset按字节赋值,int4个字节,每个字节赋值为1,就是0x01010101了
        memset( used, 0, sizeof(used));
        for( int i = 1; i <= n; ++i)
            factorial[i] = factorial[i-1] * i;
        string res = "";
        for( int i = n; i >= 1; --i){
            for( int j = 1; j <= n; ++j){
                if( j * factorial[i-1] < k)
                    continue;
                else{
                    int m = j;
                    int p = 1;
                    for( ; m; ++p){//从下往上数第m个没用过的数字
                        if( !used[p])
                            --m;
                    }
                    --p;
                    res += p + '0';
                    k = k - ((j-1) * factorial[i-1]);//修正k
                    used[p] = true;//用过了数组就标记为用过
                    break;
                }
            }
        }
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值