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,再练习一道类似题目。该题目同样可以使用DFS,先把集合里的数按升序排列好。递归截止条件为当前子集的长度与原集合的长度相等,即当前子集等于原集合。每次递归开始前都先将当前的子集加入到子集集合中,每次递归都将nums[i]加入到子集中,然后继续递归。
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
A = []
def dfs(start, length, List):
A.append(List)
if length == len(nums):
return
for i in range(start, len(nums)):
dfs(i+1, length+1, List+[nums[i]])
nums.sort()
dfs(0, 0, [])
return A