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

性能:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值