My accepted python code with explanation


  • 0
    S
    def getPermutation(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: str
        """
        if n == 1:
            return '1'
        result = ''
        candidates = [str(num) for num in range(1,n+1)]
        result = self.myget(n,k,candidates,result)
        return result
    
    def myget(self, n,k,candidates,result):
        if n == 1:
            result += candidates[0]
            return result
        #fix the first number, how many permutations for that number
        rownum = math.factorial(n-1)
        #find the index for first number
        index = (k-1)/rownum
        #find the first number
        digit = candidates[index]
        result += digit
        #remove the first number
        candidates.remove(digit)
        #recursively do the following numbers
        result = self.myget(n-1,k%rownum, candidates, result)  
        return result

Log in to reply
 

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