【LeetCode每天一題】Subsets II(子集合II)
阿新 • • 發佈:2019-05-06
class dup h+ pat list must pen res per
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.
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)
【LeetCode每天一題】Subsets II(子集合II)