My python solution...


  • 0
    S
    class Solution(object):
        import math
        def getPermutation(self, n, k):
            """
            :type n: int
            :type k: int
            :rtype: str
            """
            config0 = [ str(i) for i in range(1,n+1) ] # initial permutation!
            answer  = []
            k = k - 1 # initial permutation is indexed 0 -  indexing is starting from 0, so k = k - 1 to get correct output
            
            while n > 0: # as long as some unprocessed items in initial config
                factn = math.factorial(n-1)  # (n-1)!
                i     = (k//factn)  # i is an index of an item from config0 which will appear next in permutation, k//(n-1)!
                answer.append( config0[i] ) # add that item to answer
                config0.pop(i) # remove it from config0
                k     = k % factn # what's next k from among remaining config0
                n     = n - 1     # config0 has reduced in size (because we popped above)
            
            return ''.join(answer)

Log in to reply
 

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