Python solution


  • 0
    D

    Hope this solution is easy to understand

    import math
    class Solution(object):
        def getPermutation(self, n, k):
            """
            :type n: int
            :type k: int
            :rtype: str
            """
            used = [False for i in xrange(n)]
            return self.helper(n, k, used)
            
        def helper(self, n, k, used):
            digit = 1
            while used[digit - 1]:
                digit += 1
            if n == 1:
                return str(digit)
            
            diff = math.factorial(n - 1)
            while k > diff:
                digit += 1
                while used[digit - 1]:
                    digit += 1
                k -= diff
            used[digit - 1] = True
            ans = str(digit)
            
            return ans + self.helper(n - 1, k, used)
    

Log in to reply
 

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