[Leetcode]子集
题目描述
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
示例:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
实现代码
- 方法一:迭代
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = [[]]
for i in nums:
res += [[i] + re for re in res]
return res
- 方法二:递归回溯
- 和Leetcode-组合是一类题,不同的是,无论如何path都要加到res中
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
n = len(nums)
if n == 0:
res.append([])
return res
def dfs(begin, path):
res.append(path[:]) #无论如何path都要加到res中
for i in range(begin, n):
path.append(nums[i])
dfs(i + 1,path)
del path[-1]
dfs(0, [])
return res