【python-leetcode90-子集】子集Ⅱ

给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明:解集不能包含重复的子集。

示例:

输入: [1,2,2]
输出:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]

class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        global res
        nums.sort()
        res=[]
        tmp=[]
        self.helper(0,tmp,nums)
        return res
    def helper(self,i,tmp,nums):
        res.append(tmp)
        for j in range(i,len(nums)):
            if j>i and nums[j] == nums[j-1]:
                continue
            self.helper(j+1,tmp+[nums[j]],nums)

结果:
[[],[1],[1,2],[1,2,2],[2],[2,2]]

和子集那题很类似:

https://www.cnblogs.com/xiximayou/p/12437013.html

这里有重复的数字,核心就是标红的地方。

比如nums=[2,1,2],先对其排序为[1,2,2]

那么比如现在有[1],[2]就只需要加入一次即可:[1,2]。也就是说[1,2],这里2就不能来自接下来的2了,不然会重复。

原文地址:https://www.cnblogs.com/xiximayou/p/12450602.html