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

相关推荐
颜酱9 小时前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
m0_736919109 小时前
C++代码风格检查工具
开发语言·c++·算法
yugi9878389 小时前
基于MATLAB强化学习的单智能体与多智能体路径规划算法
算法·matlab
DuHz9 小时前
超宽带脉冲无线电(Ultra Wideband Impulse Radio, UWB)简介
论文阅读·算法·汽车·信息与通信·信号处理
Polaris北极星少女9 小时前
TRSV优化2
算法
代码游侠10 小时前
C语言核心概念复习——网络协议与TCP/IP
linux·运维·服务器·网络·算法
2301_7634724610 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
abluckyboy11 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法
园小异11 小时前
2026年技术面试完全指南:从算法到系统设计的实战突破
算法·面试·职场和发展
m0_7066532311 小时前
分布式系统安全通信
开发语言·c++·算法