题目描述:
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], [2,1,1] ]
我的思路:
跟上道题一样的,只不过列表中有重复的元素。
取巧一波,直接使用上道题代码,只不过把最后结果中的重复元素去掉就可以了。
我的代码:
class Solution:
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
avail, lev_node = nums, []
N = len(nums)
def dfs(avail, lev_node):
if len(lev_node) == N:
res.append(lev_node)
return
for i in range(len(avail)):
dfs(avail[:i] + avail[i + 1:], lev_node + [avail[i]])
dfs(avail, lev_node)
tmp = []
for x in res:
if x not in tmp:
tmp.append(x)
return tmpDiscuss:
def permuteUnique(self, nums):
ans = [[]]
for n in nums:
new_ans = []
for l in ans:
for i in xrange(len(l)+1):
new_ans.append(l[:i]+[n]+l[i:])
if i<len(l) and l[i]==n: break #handles duplication
ans = new_ans
return ans学到:
本文介绍了一种算法,用于解决含有重复元素的集合的所有唯一排列问题。通过递归深度优先搜索实现,并采用去重技巧保证结果中没有重复项。
381

被折叠的 条评论
为什么被折叠?



