Leetcode 78. Subsets

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 78: Subsets

Leetcode 78. Subsets

Leetcode 78. Subsets

[leetcode-78-Subsets]

Leetcode 78: Subsets

LeetCode78. Subsets