Python recursive solution - classical - 85ms


  • 0
    G
    class Solution:
        # @param {integer[]} nums
        # @return {integer[][]}
        # 5:56
        def permute(self, nums):
            if not nums:
                return []
    
            result, flags = [], [False] * len(nums)
            self.getPermutation(nums, result, flags, [])
    
            return result
    
        def getPermutation(self, nums, result, flags, temp):
            if len(temp) == len(nums):
                result.append(temp[:])
                return
    
            for i in range(len(nums)):
                if flags[i]:
                    continue
    
                flags[i] = True
                temp.append(nums[i])
                self.getPermutation(nums, result, flags, temp)
                temp.pop()
                flags[i] = False

  • 0
    M

    Well - Can you add some comments to explain your solution ?


  • 0
    G

    This is a classical solution for permutation, you can find more information in PIE / cc150 books (they explained this better than me ;))

    e.g. Check it out on the PIE book http://tinyurl.com/o774jsl


  • 0
    M

    thanks google !!


Log in to reply
 

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