当前位置:网站首页>【LeetCode】39、组合总和
【LeetCode】39、组合总和
2022-08-05 21:17:00 【小曲同学呀】
39. 组合总和
题目:
给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。
candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。
对于给定的输入,保证和为 target 的不同组合数少于 150 个。
示例1:
输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。
示例2:
输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]
示例3:
输入: candidates = [2], target = 1
输出: []
提示:
1 <= candidates.length <= 30
1 <= candidates[i] <= 200
candidate 中的每个元素都 互不相同
1 <= target <= 500
解题思路:
递归枚举,枚举每个数字可以选多少次。
- 1、遍历数组中的每一个数字。
- 2、递归枚举每一个数字可以选多少次,递归过程中维护一个
target变量。如果当前数字小于等于target,我们就将其加入我们的路径数组path中,相应的target减去当前数字的值。也就是说,每选一个分支,就减去所选分支的值。 - 3、当
target== 0时,表示该选择方案是合法的,记录该方案,将其加入res数组中。
递归树如下,以candidates = [2,3,6,7], target = 7为例。

递归边界:
1、 if(target < 0) ,表示当前方案不合法,返回上一层。
2、if(target == 0),方案合法,记录该方案。
参考代码:
class Solution {
List<List<Integer>> res = new ArrayList<>(); //记录答案
List<Integer> path = new ArrayList<>(); //记录路径
public List<List<Integer>> combinationSum(int[] candidates, int target) {
dfs(candidates,0, target);
return res;
}
public void dfs(int[] c, int u, int target) {
if(target < 0) return ;
if(target == 0)
{
res.add(new ArrayList(path));
return ;
}
for(int i = u; i < c.length; i++){
if( c[i] <= target)
{
path.add(c[i]);
dfs(c,i,target - c[i]); // 因为可以重复使用,所以还是i
path.remove(path.size()-1); //回溯,恢复现场
}
}
}
}

边栏推荐
- js校验日期时间的正则表达式
- npcap lookback adapter回环网卡是什么 它的作用是什么
- MySQL主从复制原理和使用
- App测试时常用的adb命令你都掌握了哪些呢?
- day15--使用postman, newman和jenkins进行接口自动化测试
- Win10怎么打开msixbundle安装包
- uni-app - 在纯 JS 文件中调用自定义弹框组件 / 封装全局 API 调用弹框组件(解决小程序、APP 无法使用 document.body.appendChild 插入组件节点)适配全端
- LeetCode 0623.在二叉树中增加一行:DFS / BFS
- Shell case: jumpserver jumper
- 与第三方iot平台IFTTT&Smartthings&Google对接开发iot物联网云服务
猜你喜欢
随机推荐
Shell(5) array
day15--使用postman, newman和jenkins进行接口自动化测试
五、kubeadm高可用
电脑系统安装Word图标变成白色怎么恢复?
BI业务分析思维:现金流量风控分析(三)风险控制
【opencv图像处理】--3.图像运算、基本变换、仿射变换
极大似然估计和交叉熵
软件性能测试有哪些性能指标?可做性能测试的软件检测机构安利
arm设备上的嵌入式开发编译环境搭建
【PCB开源分享】STC/IAP15W4K61S4开发板
如何使用Solidity和Hardhat构建你自己的NFT以及NFT交易市场
What adb commands have you mastered in app testing?
第十五天(上)&poetman的上传和下载
ZeroMQ替代ros
信息系统项目管理师---第十一章项目风险管理
89.(cesium之家)cesium聚合图(自定义图片)
【kitti】terminate called after throwing an instance of ‘YAML::BadFile‘
Configure MySQL5.7 database under linux (CentOS7) and realize remote access
dart learning record - Updating
Flexible and easy-to-use sql monitoring script part3









