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] ]
思路:这个题目有个简单版本,就是输入数字互不相同,那用简单的dfs就可以。现在出现重复的话,我们需要先将输入的数字排个序。规定碰到相同的数字nums[i] == nums[i-1], 只有当第i-1个数字用过之后,才能用i,保证了次序问题。代码如下:
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def dfs(nums,k,ans,cur,used):
#print cur, used
if k == len(nums):
ans.append(cur)
return
for i in range(0, len(nums)):
if used[i]:
continue
if i>0 and nums[i] == nums[i-1] and not used[i-1]:
continue
used[i] = 1
dfs(nums,k+1,ans,cur+[nums[i]],used)
used[i] = 0
nums.sort()
ans = []
used = [0 for i in range(0,len(nums))]
dfs(nums,0,ans,[],used)
return ans