Java [Leetcode 40]Combination Sum II
2015-12-04 22:03
441 查看
题目描述:
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
A solution set is:
解题思路:
跟前一个类似,不过每次选好当前元素后,就直接选下一个位置的元素了。并且在每次选元素之前,保证这次的元素与上次的元素不重合。
代码如下:
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,5and target
8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
解题思路:
跟前一个类似,不过每次选好当前元素后,就直接选下一个位置的元素了。并且在每次选元素之前,保证这次的元素与上次的元素不重合。
代码如下:
public class Solution { public List<List<Integer>> combinationSum2(int[] candidates, int target) { Arrays.sort(candidates); List<List<Integer>> result = new ArrayList<List<Integer>>(); getResult(result, new ArrayList<Integer>(), candidates, target, 0); return result; } public void getResult(List<List<Integer>> result, List<Integer> current, int[] candiates, int target, int start) { if (target > 0) { for (int i = start; i < candiates.length && target >= candiates[i]; i++) { if (i > start && candiates[i] == candiates[i - 1]) continue; current.add(candiates[i]); getResult(result, current, candiates, target - candiates[i], i + 1); current.remove(current.size() - 1); } } else if (target == 0) { result.add(new ArrayList<Integer>(current)); } } }
相关文章推荐
- Java并发编程系列之二:线程状态
- struts2 标签 --<<s:url >
- 【java web】--JSP原理详细剖析
- Myeclipse 2015 stable 2.0 完美破解方法
- eclipse中导入opencv
- 富文本编辑器在Java中使用
- 20个非常有用的Java程序片段
- Java编写Telnet客户端,连接到Windows的Telnet服务器,执行命令和批处理脚本
- java 字节数组取反
- Struts2学习——(五)ModelDriven使用方法及机制学习
- java 非法字符: \65279
- 用eclipse创建servlet小程序
- Java [Leetcode 39]Combination Sum
- java获取系统时间比实际时间少了8个小时的解决方法
- Java中的拦截器、过滤器、监听器
- Java中重载和重写的区别
- Jlabel实现内容自动换行
- JAVA-计算器
- struts2必备包
- Java内部类的一些总结