1 问题
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
示例 1:
输入:nums = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]
示例 2:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
2 答案
自己写的不对,回溯算法,不能刚开始就使用快慢指针对列表去重
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
# 数组内部去重,但是不太行,审题错了
nums.sort()
slow = 0
fast = 0
for i in range(len(nums)):
if nums[slow] == nums[fast]:
fast += 1
else:
nums[slow+1] = nums[fast]
slow += 1
new = nums[:slow+1]
def dfs(size, nums, path, depth, used, res):
if depth == size:
res.append(path)
return # 用返回来打断回溯
for index in range(size):
if not used[index]:
used[index] = True
dfs(size, nums, path+[nums[index]], depth+1, used, res)
used[index] = False
size=len(nums)
path=[]
res=[]
used = [False for _ in range(size)]
dfs(size, nums, path, 0, used, res)
return res
官方解,依然是回溯算法,其实加一个判断并continue就可以,return用于打断回溯
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
def dfs(size, nums, path, depth, used, res):
if depth == size:
res.append(path)
return # 用返回来打断回溯
for index in range(size):
if not used[index]:
if index>0 and nums[index] == nums[index-1] and not used[index-1]: # 加一个判断就可以,这里不写not也可以,但是算法效率会下降
continue
used[index] = True
dfs(size, nums, path+[nums[index]], depth+1, used, res)
used[index] = False
size=len(nums)
path=[]
res=[]
nums.sort()
used = [False for _ in range(size)]
dfs(size, nums, path, 0, used, res)
return res