给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:
输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
nums.sort()
self.res = []
used = [0] * len(nums)
self._help([], nums, used)
return self.res
def _help(self, tmp, nums, used):
if len(tmp) == len(nums):
self.res.append(tmp)
return
for i in range(len(nums)):
if used[i] == 1:
continue
if i > 0 and nums[i] == nums[i-1] and used[i-1] == 0:
continue
used[i] = 1
self._help(tmp+[nums[i]], nums, used)
used[i] = 0
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
size = len(nums)
if size == 0:
return []
nums.sort()
used = [False] * len(nums)
res = []
self.dfs(nums, size, 0, [], used, res)
return res
def dfs(self, nums, size, depth, path, used, res):
if depth == size:
res.append(path.copy())
return
for i in range(size):
if not used[i]:
if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
continue
used[i] = True
path.append(nums[i])
self.dfs(nums, size, depth + 1, path, used, res)
used[i] = False
path.pop()