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:])

相关推荐
haogexiaole21 分钟前
贪心算法python
算法·贪心算法
希望201735 分钟前
图论基础知识
算法·图论
m0_7135418440 分钟前
systemverilog如何解决不能使用变量索引来进行位选择的范围指定
算法·systemverilog
七牛云行业应用1 小时前
深度解析强化学习(RL):原理、算法与金融应用
人工智能·算法·金融
和编程干到底1 小时前
数据结构 栈和队列、树
数据结构·算法
纪元A梦1 小时前
贪心算法在GNN邻域采样问题中的深度解析
算法·贪心算法
宇钶宇夕1 小时前
西门子 S7-200 SMART PLC 核心指令详解:从移位、上升沿和比较指令到流水灯控制程序实战
运维·算法·自动化
爱编程的化学家2 小时前
代码随想录算法训练营第十一天--二叉树2 || 226.翻转二叉树 / 101.对称二叉树 / 104.二叉树的最大深度 / 111.二叉树的最小深度
数据结构·c++·算法·leetcode·二叉树·代码随想录
tqs_123452 小时前
redis zset 处理大规模数据分页
java·算法·哈希算法
吃着火锅x唱着歌3 小时前
LeetCode 1446.连续字符
算法·leetcode·职场和发展