LeetCode-algorithms 47. Permutations II

题目:

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


结果:


tim
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值