Leetcode #40. Combination Sum II 组合求和2 解题报告
2016-04-11 23:57
399 查看
1 解题思想
这道题是昨天的升级版,先看看这个Leetcode #39. Combination Sum 组合求和 解题报告
这道题的改变就是每个位置的数只能用一次了,但是如果本身就给了多个的话就无所谓。
基本方法一样,关键是对于重复的那里处理:
请看我代码里面的这一条
关键在于这部防止重复,规则就是排序后,如果当前位置i的数字和i-1的一样,那么必须要i用过后,i-1才能用,不然必须跳过,所有都是
2 原题
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.Each number in C may only be used once in the combination.
Note:
All numbers (including target) will be positive integers.
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
3 AC解
public class Solution { List<List<Integer>> result; boolean flag[]; int candidates[]; int target; //递归寻找位置 public void find(int index,int tmp){ if(tmp==target){ //输出结果 List<Integer> list=new ArrayList<Integer>(); for(int i=0;i<=index;i++){ if(flag[i]){ list.add(candidates[i]); } } result.add(list); } else{ for(int i=index+1;i<candidates.length;i++){ //关键在于这部防止重复,规则就是排序后,如果当前位置i的数字和i-1的一样,那么必须要i用过后,i-1才能用,不然必须跳过,所有都是 if(i>0 && candidates[i]==candidates[i-1] && flag[i-1]==false) continue; if(tmp+candidates[i]<=target){ //对于满足条件的前进 flag[i]=true; find(i,tmp+candidates[i]); flag[i]=false; } else{ break; } } } } public List<List<Integer>> combinationSum2(int[] candidates, int target) { result = new ArrayList<List<Integer>>(); Arrays.sort(candidates); flag = new boolean[candidates.length]; this.candidates=candidates; this.target=target; find(-1,0); return result; } }
相关文章推荐
- Qt面向对象的程序设计(二)
- 监听器
- SQLAlchemy 操作数据库
- hdu1495
- [前端 4] 使用Js实现图片上传预览
- [前端 4] 使用Js实现图片上传预览
- popupwindow的学习
- 单调递增子序列(二)(nyoj214)
- 1003快速排序
- java多态和动态绑定
- 射频中经常是用50欧姆作为阻抗匹配的标准的原因
- 线程运行机制
- WPF
- JS数组方法汇总 array数组元素的添加和删除
- Map、Set、List、Queue、Stack的特点与用法
- 网页四--按钮反应
- Centos搭建git服务器
- zeroclipboard复制反斜杠时不正确的解决办法
- Intellij Idea 使用笔记
- 详细分析HFSS、ADS、CST各自优缺点及应用范围,看看你到底应该学习哪种仿真?