leetcode100子集
目录
【leetcode100】子集
1、题目描述
给你一个整数数组
nums
,数组中的元素
互不相同
。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
2、初始思路
2.1 思路
与前几篇的回溯不同,求子集需要保留所有节点的值,而不是只保留叶子结点的值。
因此,在backtracking函数中,应该直接将path加到res中,以将每个节点都进行保留。
res.append(path.copy())
2.2 代码
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
path = []
def backtracking(nums, startIndex):
res.append(path.copy())
for i in range(startIndex, len(nums)):
path.append(nums[i])
backtracking(nums, i+1)
path.pop()
backtracking(nums, 0)
return res