首页 > 代码库 > Leetcode 78. Subsets

Leetcode 78. Subsets

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()

 

Leetcode 78. Subsets