[LC] 47. Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

Time: O(N!)
Space: O(N)

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        res = []
        if nums is None or len(nums) == 0:
            return res
        self.dfs(nums, 0, res)
        return res
    
    def dfs(self, nums, level, res):
        if level == len(nums):
            res.append(list(nums))
            return
        my_set = set()
        for i in range(level, len(nums)):
            if nums[i] not in my_set:
                my_set.add(nums[i])
                nums[i], nums[level] = nums[level], nums[i]
                self.dfs(nums, level + 1, res)
                nums[i], nums[level] = nums[level], nums[i]

 

猜你喜欢

转载自www.cnblogs.com/xuanlu/p/11664671.html