给定一个可能包含重复元素的整数数组 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://cloud.tencent.com/developer/article/1686190
这里有重复的数字,核心就是标红的地方。
比如nums=2,1,2,先对其排序为1,2,2
那么比如现在有1,2就只需要加入一次即可:1,2。也就是说1,2,这里2就不能来自接下来的2了,不然会重复。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有