Leetcode: Permutation Sequence

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

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.

你可能感兴趣的:(Leetcode: Permutation Sequence)