【LeetCode每天一题】Subsets II(子集合II)
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。Example:
Input: [1,2,2]
Output:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
思路
这道题和之前做的排列组合很相似,我们都可以使用深度优先遍历来进行组合,因为相同的数字不同的组合顺序看作相同的集合,所以这里我们需要加一些判定条件当后面的数组相同的时候就进行组合直接跳过。这样最后就可以得到子集合结果。详细见代码。
解决代码
最初想到的解法
1 class Solution(object): 2 def subsetsWithDup(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: List[List[int]] 6 """
7 if not nums: # nums为空直接返回
8 return [[]] 9 nums.sort() # 将nums进行排序,
10 res = [] # 记录子集合的列表
11 for i in range(len(nums)+1): # 从一个元素开始进行组合。
12 self.permution(nums, [], res, i) 13 return res 14
15 def permution(self, nums, path, res, count): 16 if len(path) == count: # 满足条件将子集合添加进结果集中
17 res.append(path) 18 return
19 for i in range(len(nums)): 20 if i >0 and nums[i] == nums[i-1]: # 如果当前元素和前一个元素相等的话,直接跳过。
21 continue
22 self.permution(nums[i+1:], path+[nums[i]], res, count)
改进之后的解法
class Solution(object): def subsetsWithDup(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """
if not nums: return [[]] nums.sort() res = [] self.permution(nums, [], res, 0) # 去掉循环, 直接从0开始 return res def permution(self, nums, path, res, count): if len(path) == count: # 依次进行添加 res.append(path) for i in range(len(nums)): if i >0 and nums[i] == nums[i-1]: continue self.permution(nums[i+1:], path+[nums[i]], res, count+1)

更多精彩