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.

知識補充:

#divmod函數
//本函數是實現a除以b,然後返回商與餘數的元組。如果兩個參數a,b都是整數,那麼會採用整數除法,結果相當於(a//b, a % b)。如果a或b是浮點數,相當於(math.floor(a/b), a%b)。
index, k = divmod(k, n)

參考答案(C++):

class Solution {

public:
    string getPermutation(int n, int k) {
        int i,j,f=1;
        // left part of s is partially formed permutation, right part is the leftover chars.
        string s(n,'0');
        for(i=1;i<=n;i++){
            f*=i;
            s[i-1]+=i; // make s become 1234...n
        }
        for(i=0,k--;i<n;i++){
            f/=n-i;
            j=i+k/f; // calculate index of char to put at s[i]
            char c=s[j];
            // remove c by shifting to cover up (adjust the right part).
            for(;j>i;j--)
                s[j]=s[j-1];
            k%=f;
            s[i]=c;
        }
        return s;
    }
};

性能:

這裏寫圖片描述

參考答案(python):

import math
class Solution:
    # @param {integer} n
    # @param {integer} k
    # @return {string}
    def getPermutation(self, n, k):
        numbers = range(1, n+1)
        permutation = ''
        k -= 1
        while n > 0:
            n -= 1
            # get the index of current digit
            index, k = divmod(k, math.factorial(n))
            permutation += str(numbers[index])
            # remove handled number
            numbers.remove(numbers[index])

        return permutation

性能:

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章