加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

【python-leetcode90-子集】子集Ⅱ

发布时间:2020-12-20 09:54:20 所属栏目:Python 来源:网络整理
导读:给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。 说明:解集不能包含重复的子集。 示例: 输入: [1,2,2] 输出: [ [2], [1], [1,2], [2, [] ] ? class Solution: def subsetsWithDup(self,nums: List[int]) - List[List[int]]:

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

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

示例:

输入: [1,2,2]
输出:
[
[2],
[1],
[1,2],
[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,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],[2,2]]

和子集那题很类似:

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读