Leetcode_permutation-sequence(c++ and python version)

62 篇文章 0 订阅
52 篇文章 0 订阅

地址:http://oj.leetcode.com/problems/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):

  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.

思路:permutation的规则,每次都是连续升序。归纳一下就是,只有之前有(n-1)!个permutations时,第1个数才增1.(排列数:n-1个数有(n-1)!的排列)。

根据这个构造算法

c++ 参考代码:

class Solution {
public:
    int factorial(int num)
    {
        int ans = 1;
        while(num>=2)
            ans *= num--;
        return ans;
    }
    string getPermutation(int n, int k) {
        string ans = "";
        vector<int>vec(n, 0);
        for(int i = 0; i<n; ++i)
            vec[i] = i+1;
        int idx = 0, fa = 0;
        while(!vec.empty())
        {
            fa = factorial(n-1);
            if(k)
                idx = (k-1) / fa;
            else
                idx = n-1;
            ans += vec[idx] + '0';
            vec.erase(vec.begin()+idx);
            k = k % fa;
            --n;
        }
        return ans;
    }
};

python参考代码:

class Solution:
    # @return a string
    def getPermutation(self, n, k):
        arr = range(1, n+1)
        ans = ""
        while arr:
            cur = (k-1) // math.factorial(n-1)
            ans += str(arr[cur])
            k %= math.factorial(n-1)
            n -= 1
            arr.pop(cur)
        return ans

话说python取list中的-1属性太好用了,代码这么简洁。c++里还没有直接算阶乘的。

但是python运行时间228ms, c++运行时间才8ms.

是不是OJ里引入了太多库了,实际上可能差不了这大。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值