Leetcode 78. Subsets I and II
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
思路: 使用DFS,找出所有的 size 为 1,2,3, ..., n 的subset。
1 class Solution(object): 2 def subsets(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: List[List[int]] 6 """ 7 n = len(nums) 8 ans = [[]] 9 10 for k in range(1,n+1): 11 cur = [] 12 self.DFS(nums, ans, [], k) 13 14 return ans 15 16 def DFS(self, nums, ans, line, k): 17 if len(line) == k: 18 ans.append([x for x in line]) 19 return 20 21 for i, x in enumerate(nums): 22 line.append(x) 23 self.DFS(nums[i+1:], ans, line, k) 24 line.pop()
Given a collection of integers that might contain duplicates, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,2]
, a solution is:
[ [2], [1], [1,2,2], [2,2], [1,2], [] ]
subsets II这道题和第一题差不多,只不过nums里面有重复的数字,但是subset中不能有重复的情况。比如考虑例子[1,2,2,3],如果第一个元素已经取了2,那么第一个元素肯定就不能再取2了。所以在for loop中的下个iteration中要判断一下,看看是不是和上一个元素相同,如果相同的话,直接跳过。
1 class Solution(object): 2 def subsetsWithDup(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: List[List[int]] 6 """ 7 nums.sort() 8 n = len(nums) 9 ans = [[]] 10 11 for k in range(1,n+1): 12 cur = [] 13 self.DFS(nums, ans, [], k) 14 15 return ans 16 17 def DFS(self, nums, ans, line, k): 18 if len(line) == k: 19 ans.append([x for x in line]) 20 return 21 22 for i, x in enumerate(nums): 23 if i>0 and nums[i] == nums[i-1]: 24 continue 25 else: 26 line.append(x) 27 self.DFS(nums[i+1:], ans, line, k) 28 line.pop() 29