leetcode hot 100搜索回溯

39. 组合总和

已解答

中等

相关标签

相关企业

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

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

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

import copy

class Solution(object):

def combinationSum(self, candidates, target):

"""

:type candidates: Listint

:type target: int

:rtype: ListList\[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,candidatesindex:)

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,candidatesindex:)

相关推荐
yszaygr21382 小时前
Verilog参数化游程编码RLE模块
算法
望易2 小时前
刚设计的大模型架构-双域耦合认知框架
算法·架构
复杂网络6 小时前
多个 Claude Code 与多个 Codex 协同工作:设计与实现方案
算法
HjhIron1 天前
面试常客:字符串算法从入门到进阶
算法·面试
吴佳浩1 天前
DeepSeek DSpark:Confidence-Scheduled Speculative Decoding 技术解析
人工智能·算法·deepseek
触底反弹1 天前
🧠 搞懂 Token,才算真正入门大模型——从分词原理到 Embedding 语义实战
javascript·人工智能·算法
vivo互联网技术1 天前
ICLR 2026 | 基于后验采样的图像恢复方法LearnIR:人脸去阴影、去雾
人工智能·算法·aigc
浮生望1 天前
JS字符串与回文算法:从包装类到双指针的面试进阶之路
javascript·算法
黄敬峰1 天前
面试必刷:从JS底层包装类到双指针,彻底搞懂字符串与回文算法
算法
地平线开发者2 天前
J6B vio scenario sample
算法