Leetcode之回溯法专题-40. 组合总和 II(Combination Sum II)

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

说明:

  • 所有数字(包括目标数)都是正整数。
  • 解集不能包含重复的组合。

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
  [1,2,2],
  [5]
] 分析:跟上一题(Leetcode.39)类似,区别在于这题每个数字只能用一次。还是同样的思想(回溯法),
大于target的直接跳过,先排序。 回溯法 -> 举例
candidates = [10,1,2,7,6,1,5], target = 8 , 排序后candidates = [1,1,2,5,6,7,10]
首先,入口是dfs(index=0)
选第一个1,这里我们标记为step1,
接着继续选取第二个1,标记为step2,
继续选2,step3,
选5,标记为step4,
此时已超出target=8(此时为9),故大于了target,根据代码return到上一步,返回到step4,不选5,选6
超出,退回,不选6,选7,超出,退回,选10,超出,退回。(我的AC代码里在后面还是循环了,所以浪费了很多时间,可以发现大于的就直接返回,不进入下一步了) 以此类推。因此第一个产生出来的答案应该是 1 2 5


AC代码:
class Solution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
dfs(candidates,target,0,target,new ArrayList<Integer>());
return ans;
} public void dfs(int[] candidates,int target,int index,int balance,ArrayList<Integer> list){
if(balance<0){
return;
}
if(balance==0){
if(!ans.contains(list)) ans.add(new ArrayList<Integer>(list));
return;
} if(index>=candidates.length){
return;
}
int num = candidates[index]; list.add(num);
dfs(candidates,target,index+1,balance-num,list);
list.remove(list.size()-1);
dfs(candidates,target,index+1,balance,list); }
}

 




最新文章

  1. Windows下虚拟机安装Ubuntu15.10 Destop简易操作过程
  2. Apache问题处理服务器访问不了
  3. easyUI combobox 控件 使用
  4. HashMap源码阅读笔记(基于jdk1.8)
  5. 【非原创】IOS 验证文字是否是中文
  6. excle心得及部分应用案例
  7. August 3rd, 2016, Week 32nd, Wednesday
  8. 解决zabbix图中出现中文乱码问题 图中的中文会变成方块
  9. jquery闭包的使用
  10. centos7 php7 安装composer时Failed to decode zlib stream解决办法
  11. c++ 中关于int,unsigned int , short的关系与应用
  12. Bellman 算法
  13. Queue(队列)
  14. DLP底座(威创定制)
  15. JS菜单条智能定位效果
  16. RestServer 2.0 正式版发布
  17. pycharm远程debug(内网环境,跳板机)
  18. 技术的热门度曲线:GHC
  19. 在cef中使用自定义协议(scheme)
  20. vue Axios 封装与配置项

热门文章

  1. Java&amp;mysql:过滤文件内容,将新文件内容存入mysql数据库
  2. cookbook_模块和包
  3. jsp数据交互(一).2
  4. TIJ读书笔记-第21章-并发
  5. 【iOS】edgesForExtendedLayout
  6. .net core开发从未如此简单,比abp更接地气
  7. 使用ForkJoinPool来多线程的拆分任务,执行任务,合并结果。
  8. 并发编程(4)——AbstractQueuedSynchronizer
  9. .netcore持续集成测试篇之开篇简介及Xunit基本使用
  10. SpringMVC的流程