Problem
# Given a collection of numbers that might contain duplicates,
# return all possible unique permutations.
#
# For example,
# [1,1,2] have the following unique permutations:
# [1,1,2], [1,2,1], and [2,1,1].
AC
# DFS
class Solution():
def permuteUnique(self, x):
return self.dfs(x)
def dfs(self, x):
if len(x) == 0:
return []
if len(x) == 1:
return [x]
pre, cur = self.dfs(x[:-1]), []
for p in pre:
for i in range(len(x)):
if p[:i] + [x[-1]] + p[i:] not in cur: # 加上一句去重
cur.append(p[:i] + [x[-1]] + p[i:])
return cur
if __name__ == "__main__":
assert Solution().permuteUnique([1, 1, 2]) == [[2, 1, 1], [1, 2, 1], [1, 1, 2]]