Python math Solution


  • 1
    C

    import math
    class Solution(object):

    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        #corner cases
        if n==0:
            return ""
        if n==1 and k==1:
            return "1"
        if n==1 and k!=1:
            return ""
        #regular cases
        ans = ""
        nums=range(1,n+1)
        for i in xrange(1,n):
            f = math.factorial(n-i)
            index = (k-1)/f+1
            digit=nums.pop(index-1)
            ans = ans+str(digit)
            k = k- (index-1)*f
        ans = ans+str(nums[0])
        return ans

Log in to reply
 

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