44ms python solution


  • 5
    J
    from math import factorial  
    class Solution(object):
    
        def getPermutation(self, n, k):
            """
            :type n: int
            :type k: int
            :rtype: str
            """
            res = []
            nums = [i for i in xrange(1, n+1)]
            while n-1 >= 0:
                num, k = k/factorial(n-1), k % factorial(n-1)
                if k > 0:
                    res.append(str(nums[num]))
                    nums.remove(nums[num])
                else:
                    res.append(str(nums[num-1]))
                    nums.remove(nums[num-1])
    
                n -= 1
    
            return ''.join(res)

  • 0
    K

    redundant computation of factorials


Log in to reply
 

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