A short clear Python algorithm using a recursive generator?


  • 0
    M
    from copy import copy
    
    
    def permutations(nums, i=0):
        if i >= len(nums) - 1:
            yield copy(nums)
            return
        swap_with = i
        while swap_with < len(nums):
            nums[i], nums[swap_with] = nums[swap_with], nums[i]
            for perm in permutations(nums, i + 1):
                yield perm
            swap_with += 1
            while swap_with < len(nums) and nums[swap_with] == nums[i]:
                swap_with += 1
    
        cur = i + 1
        while cur < len(nums):
            nums[cur - 1], nums[cur] = nums[cur], nums[cur - 1]
            cur += 1
    
    
    class Solution:
        # @param {integer[]} nums
        # @return {integer[][]}
        def permuteUnique(self, nums):
            nums.sort()
            return list(permutations(nums))

Log in to reply
 

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