Leetcode_permutation-sequence(c++ and python version)

来源:互联网 发布:知豆电动汽车电池质保 编辑:程序博客网 时间:2024/06/08 03:09

地址: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
原创粉丝点击