<BackTracking> dfs: 39 40
2024-09-04 02:15:47
39. Combination Sum
Combination,组合问题用DFS罗列全部的答案。
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
if(candidates == null || candidates.length == 0) return res;
dfs(candidates, target, 0, res, new ArrayList<Integer>());
return res;
} //1.定义
private void dfs(int[] candidates, int target, int index, List<List<Integer>> res, List<Integer> subset){
//3.出口
if(target == 0){
res.add(new ArrayList<Integer>(subset));
return;
}
if(target < 0){
return;
}
//2.拆解
for(int i = index; i < candidates.length; i++){
subset.add(candidates[i]);
dfs(candidates, target - candidates[i], i, res, subset);
subset.remove(subset.size() - 1);
} }
}
40. Combination Sum II
1. 为了防止candidates[ ]中的数字被重复使用,DFS中的index使用 i + 1。
2.防止答案中出现重复的数字使用情况,
if(i > index && candidates[i] == candidates[i - 1]) continue;
即当前层的数字只能被重复使用一次。
class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<>();
if(candidates == null || candidates.length == 0) return res;
Arrays.sort(candidates);
dfs(candidates, target, 0, res, new ArrayList<>());
return res;
} private void dfs(int[] candidates, int target, int index, List<List<Integer>> res, List<Integer> subset){
//出口
if(target == 0){
res.add(new ArrayList<Integer>(subset));
return;
}
if(target < 0){
return;
}
//拆解
for(int i = index; i < candidates.length; i++){
if(i > index && candidates[i] == candidates[i - 1]) continue;
subset.add(candidates[i]);
dfs(candidates, target - candidates[i], i + 1, res, subset);
subset.remove(subset.size() - 1);
}
}
}
最新文章
- PXE+Kickstart+DHCP+TFTP实现无人值守安装操作系统
- iTextSharp简单生成pdf和操作pdf添加水印
- Android菜鸟成长记11 -- sqlite数据库的设计和升降级
- mysql 触发器的创建 修改 删除
- Oracle HS (Heterogeneous Services)深入解析 及协同Gateway工作流程(转)
- Linux C 程序 字符串运算符-表达式(TWO)
- 完全背包的变形POJ1252
- 混合app
- JDK配置测试
- 29.Django session
- python入门(12)dict
- 洛谷P2336 喵星球上的点名
- Java NIO学习笔记---Channel
- Final互评------《I do》---- 二次元梦之队
- JavaScript数组与字符串常用方法总结
- Java GC、新生代、老年代
- django之管理静态文件
- 【数据结构】10分钟教你用栈求解迷宫老鼠问题超详细教程附C++源代码
- [原]零基础学习SDL开发之在Android使用SDL2.0渲染PNG图片
- iOS tabbar 属性
热门文章
- 数据仓库003 - 复习Linux shell命令 - 用户用户组 sudo 权限 du-sh find
- 项目整合SpringDataRedis
- Python机器学习笔记 Grid SearchCV(网格搜索)
- ML.NET调用Tensorflow模型示例——MNIST
- PHP--常用配置项
- ArcGIS Server 地图发布请求分析
- MVC 创建Controllers 发生 EntityType has no key defined error
- scrapy框架抓取表情包/(python爬虫学习)
- STP生成树理解
- Vue.js 源码分析(七) 基础篇 侦听器 watch属性详解