Python solution using generators


  • 0
    A

    premute_ is a helper function which returns a generator producing permutations of nums. In permute, we just use list to turn this generator into a list.

    class Solution(object):
        
        def permute_(self, nums):
            if len(nums) == 0:
                yield list()
            elif len(nums) == 1:
                yield list(nums)
            else:
                a = nums[0]
                for p in self.permute_(nums[1:]):
                    for i in range(len(p)+1):
                        l = []
                        l.extend(p[:i])
                        l.append(a)
                        l.extend(p[i:])
                        yield l 
    
                
            
        def permute(self, nums):
            """
            :type nums: List[int]
            :rtype: List[List[int]]
            """
            return list(self.permute_(nums))
    

Log in to reply
 

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