LeetCode 60. Permutation Sequence第k个排列

265 篇文章 1 订阅
231 篇文章 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.

Note: Given n will be between 1 and 9 inclusive.

 

Three problems:

1. overly dependent on next_permutation, TLE

2. How to rearrange after k/factorial is used

3. k--

Python Version:

class Solution:
    def getPermutation(self, n, k):
        res = [i+1 for i in range(n)]
        fac = [1 for i in range(n+1)]
        for i in range(2,n+1):
            fac[i] = fac[i-1]*i
        k -= 1
        for i in range(n):
            off,nk = divmod(k,fac[n-1-i])
            num = res[i+off]
            res[i+1:off+i+1] = res[i:i+off]
            res[i] = num
            k = nk
        return ''.join(str(num) for num in res)
s = Solution()
print(s.getPermutation(3, 3))

C++ version:

class Solution {
 public:
  string getPermutation(int n, int k) {
    vector<int> factorial(n, 1);
    string res(n, '1');
    for (int i = 1; i < n; ++i) {
      factorial[i] = factorial[i-1]*i;
      res[i] += i;
    }
    --k;
    for (int i = 0; i < n; ++i) {
      int tmp = k / factorial[n - 1 - i];
      char ch = res[i + tmp];
      for (int j = tmp + i; j > i; --j)
        res[j] = res[j - 1];
      res[i] = ch;
      k = k % factorial[n - 1 - i];
    }
    return res;
  }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值