90. 子集 II

本文详细解析了LeetCode上90.子集II题目,针对包含重复元素的整数数组,介绍了如何通过回溯法避免重复子集的生成,并提供两种Python实现方式。

90. 子集 II

题意

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

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

示例:

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

解题思路

因为加进了重复元素,那么就有可能出现重复的子集,需要在加入到结果之前进行判断是否存在(首先要进行排序,保证每个子集都是有序的),使用的思路和1是类似的;

实现

class Solution(object):
def subsetsWithDup(self, nums):
       """
      :type nums: List[int]
      :rtype: List[List[int]]
      """
       def backtracking(index, path):
           if path not in res:
               res.append(path)
           for i in range(index, len(nums)):
               backtracking(i+1, path+[nums[i]])
               
       res = []
       nums.sort()
       backtracking(0, [])
       return res

   def subsetsWithDup(self, nums):
       """
      :type nums: List[int]
      :rtype: List[List[int]]
      """
       # set中无法放set
       res = {()}
       for num in sorted(nums):
           for item in res.copy():
               res.add(tuple(list(item)+[num]))
       return [list(item) for item in res]

转载于:https://www.cnblogs.com/George1994/p/7399878.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值