解
递归 深度优先遍历dfs
- 排序 可通过比较前一个数来避免重复排列
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
# 排序
nums.sort()
result = list()
path = list()
self.dfs(nums, path, result)
return result
def dfs(self, nums, path, result):
if len(nums) == 0:
result.append(path)
else:
for i in range(len(nums)):
# 避免重复的全排列
if i > 0 and nums[i] == nums[i - 1]:
continue
self.dfs(nums[:i] + nums[i + 1:], path + [nums[i]], result)