LeetCode 78. Subsets 20170606
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
LeetCode 78. Subsets 20170606