您的位置:首页 > 产品设计 > UI/UE

Leetcode: Permutation Sequence

2015-09-09 08:50 507 查看

Question

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.

Note: Given n will be between 1 and 9 inclusive

Solution

[code]class Solution(object):
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """

        if n<=0 or k<0:
            return ''

        res = []
        k -= 1 
        factorial = 1
        for ind in range(2,n):
            factorial *= ind

        nums = range(1,n+1)
        round = n-1
        while round>=0:
            index = k/factorial
            k %= factorial
            res.append(nums[index])
            del nums[index]
            if round>0:
                factorial /= round
            round -= 1

        res = [str(elem) for elem in res]
        res = ''.join(res)
        return res


The thing I need to notice is that k should be decreased by 1 first.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: