47. 全排列 II


官方链接

https://leetcode-cn.com/problems/permutations-ii

给定一个可包含重复数字的序列,返回所有不重复的全排列。

示例:

输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1] ]

视频资源

解法一

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
      self.res = []
      self.used = [False] * len(nums)
      self.dfs(sorted(nums), [])
      return self.res

    def dfs(self, nums, temp):
      if len(nums) == len(temp):
        self.res.append(temp[:])

      for i in range(len(nums)):
        if self.used[i]: continue
        if i > 0 and nums[i] == nums[i-1] and self.used[i-1]: continue
        self.used[i] = True
        temp.append(nums[i])
        self.dfs(nums, temp)
        self.used[i] = False
        temp.pop()