力扣 39. 组合总和

回溯思想, dfs实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def combinationSum(candidates, target):
if not candidates: return []
res, cand_len = [], len(candidates)
def dfs(target, combins, idx, begin):
target -= candidates[idx]
combins.append(candidates[idx])
if target <= 0:
if target == 0:
res.append(combins)
return
for i in range(begin, cand_len):
dfs(target, combins.copy(), i, i)

for i in range(cand_len):
dfs(target, [], i, i)

# print(res)
return res
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信