题目:
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] ]
思考:
这一题跟之前的一46题Permutations很类似,都是去求这个数组的一个排列组合;但是与46题不同的是,这里的原始数组是允许有重复数字的,而46是不重复数字的,这样我们就需要避免在结果中出现重复的结果。这里我依然使用了BFS去遍历整棵树,但是在构建树的时候,在往下扩展子节点的时候,需要注意不要有重复的子节点;这里我用的方法是使用字典去记录“该数字剩下可取”的数目,每一个节点存放着[当前状态]和[数字剩下可取数目]这样的pair,整棵树扩展完后,所有的叶子节点就是结果了。
代码:
import copy
def getDict(nums,num):
temp_dict = copy.copy(nums)
temp_dict[num] -= 1
return temp_dict
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
result_list = []
src_dict = {}
for n in nums:
if n not in src_dict:
src_dict[n] = 0
src_dict[n] += 1
for n in src_dict:
result_list.append([[n],getDict(src_dict,n)])
while len(result_list) != 0:
state = result_list.pop()
if len(state[0]) == len(nums):
result.append(state[0])
else:
for n in state[1]:
if state[1][n] > 0:
result_list.append([state[0]+[n],getDict(state[1],n)])
return result
结果: