子集

子集

1、题目

图1

2、题解

回溯法

设定一个tmp为子集,用来存放每次递归获得的数组,作为回溯的节点。遍历给定的数组,利用递归进行枚举和回溯。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
n = len(nums)
tmp = []

def dfs(i):
res.append(tmp[:])
if i == n:
return

for j in range(i,n):
tmp.append(nums[j])
dfs(j+1)
tmp.pop()

dfs(0)
return res

子集
http://example.com/2024/04/12/子集/
作者
Z Z
发布于
2024年4月12日
许可协议