classSolution:def__init__(self):
self.n =None
self.v =None
self.tmp =()
self.tmp_ans =[]defpermuteUnique(self, nums):
self.n =len(nums)
self.v =[Falsefor _ inrange(self.n)]
self.tmp =[0for _ inrange(self.n)]
self.dfs(nums,0)
tt =list(set([tuple(t)for t in self.tmp_ans]))
ans =[list(t)for t in tt]return ans
defdfs(self, nums, depth):if depth == self.n:
self.tmp_ans.append(self.tmp.copy())returnelse:for i inrange(self.n):ifnot self.v[i]:
self.v[i]=True
self.tmp[depth]= nums[i]
self.dfs(nums, depth +1)
self.v[i]=Falseif __name__ =='__main__':
a =[1,1,2]
s = Solution()print(s.permute(a))
result
[[1, 2, 1], [2, 1, 1], [1, 1, 2]]
简易版
import itertools
classSolution:defpermuteUnique(self, nums):
tmp =list(itertools.permutations(nums))
tt =list(set([t for t in tmp]))
ans =[list(t)for t in tt]return ans
if __name__ =='__main__':
a =[1,1,2]
s = Solution()print(s.permuteUnique(a))