Pretty simple Python


  • 0
    def getPermutation(self, n, k):
        if n == 1: return '1'
        # p: permutation count at level
        N, p = range(1, n+1), reduce(lambda x,y: x*y, range(1,n))
        i = n-1 # permutation level
        k -= 1 # offsetting by 1 to account for initial state
        res = []
        while k:
            v = k // p
            res.append(str(N[v]))
            del N[v]
            k, p, i = k % p, p / i, i - 1
        res.extend([str(i) for i in N]) # default order for left overs
        return ''.join(res)

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.