Thursday, September 18, 2014

Leetcode: Permutation Sequence @Python

class Solution:
    # @return a string
    def getPermutation(self, n, k):
        rst=''
        crt=k-1
        num=[str(i+1) for i in range(n)]
        for i in reversed(range(n)):
            digit=num[crt//math.factorial(i)]
            if crt!=0:
                rst=rst+digit
                num.remove(digit)
            else:
                rst=rst+''.join(num)
                break
            crt=crt%math.factorial(i)
        return rst

No comments :

Post a Comment