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);
}
}
}

最新文章

  1. PXE+Kickstart+DHCP+TFTP实现无人值守安装操作系统
  2. iTextSharp简单生成pdf和操作pdf添加水印
  3. Android菜鸟成长记11 -- sqlite数据库的设计和升降级
  4. mysql 触发器的创建 修改 删除
  5. Oracle HS (Heterogeneous Services)深入解析 及协同Gateway工作流程(转)
  6. Linux C 程序 字符串运算符-表达式(TWO)
  7. 完全背包的变形POJ1252
  8. 混合app
  9. JDK配置测试
  10. 29.Django session
  11. python入门(12)dict
  12. 洛谷P2336 喵星球上的点名
  13. Java NIO学习笔记---Channel
  14. Final互评------《I do》---- 二次元梦之队
  15. JavaScript数组与字符串常用方法总结
  16. Java GC、新生代、老年代
  17. django之管理静态文件
  18. 【数据结构】10分钟教你用栈求解迷宫老鼠问题超详细教程附C++源代码
  19. [原]零基础学习SDL开发之在Android使用SDL2.0渲染PNG图片
  20. iOS tabbar 属性

热门文章

  1. 数据仓库003 - 复习Linux shell命令 - 用户用户组 sudo 权限 du-sh find 
  2. 项目整合SpringDataRedis
  3. Python机器学习笔记 Grid SearchCV(网格搜索)
  4. ML.NET调用Tensorflow模型示例——MNIST
  5. PHP--常用配置项
  6. ArcGIS Server 地图发布请求分析
  7. MVC 创建Controllers 发生 EntityType has no key defined error
  8. scrapy框架抓取表情包/(python爬虫学习)
  9. STP生成树理解
  10. Vue.js 源码分析(七) 基础篇 侦听器 watch属性详解