原题
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
解法1
使用组合, 从列表里分别取0,1,…n个数, 将结果放到res里, 由于itertools.combination返回的是tuple, 我们需要转化为list.
Time: O(n) + O(m), m是组合列表的长度
Space: O(1)
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
for i in range(len(nums)+1):
res.extend(list(itertools.combinations(nums, i)))
res = [list(tup) for tup in res]
return res
解法2
深度优先搜索, 从空集开始, 依次将path放入res里
Time: O(n) + O(m), m是组合列表的长度
Space: O(1)
class Solution:
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
self.dfs(nums, 0, [], res)
return res
def dfs(self, nums, index, path, res):
res.append(path)
for i in range(index, len(nums)):
self.dfs(nums, i+1, path+[nums[i]], res)