leetcode hot 100搜索回溯

39. 组合总和

已解答

中等

相关标签

相关企业

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

import copy

class Solution(object):

def combinationSum(self, candidates, target):

"""

:type candidates: List[int]

:type target: int

:rtype: List[List[int]]

"""

当成一棵树来遍历回溯条件是大于target

self.ret = []

def dfs(target , current,current_list,candidates):

if current==target:

self.ret.append(copy.deepcopy(current_list))

elif current>target:

return

else:

for index,i in enumerate(candidates):

current+=i

current_list.append(i)

dfs(target,current,current_list,candidates[index:])

del current_list[-1]

current-=i

current = 0

current_list = []

dfs(target , current,current_list,candidates)

return self.ret

需要注意的是,candidates需要每次只能搜索到后面的dfs(target,current,current_list,candidates[index:])

相关推荐
byzh_rc29 分钟前
[认知计算] 专栏总结
线性代数·算法·matlab·信号处理
qq_433554541 小时前
C++ manacher(求解回文串问题)
开发语言·c++·算法
歌_顿1 小时前
知识蒸馏学习总结
人工智能·算法
圣保罗的大教堂1 小时前
leetcode 1161. 最大层内元素和 中等
leetcode
闲看云起1 小时前
LeetCode-day6:接雨水
算法·leetcode·职场和发展
没学上了2 小时前
VLM_一维离散卷积与二维离散卷积(还是复习感觉还行)
算法
黛色正浓2 小时前
leetCode-热题100-贪心合集(JavaScript)
javascript·算法·leetcode
轻微的风格艾丝凡2 小时前
嵌入式定时器计时技巧:用有符号数省略溢出判断的底层逻辑与实践
数据库·算法·dsp开发·嵌入式软件
No0d1es2 小时前
2025年12月 GESP CCF编程能力等级认证C++四级真题
算法·青少年编程·等级考试·gesp·ccf
CodeByV3 小时前
【算法题】快排
算法