Combination Sum II —— LeetCode
2015-05-29 16:18
357 查看
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:
题目大意:跟上一题类似,但是有点区别就是候选集中的元素只能出现一次。
解题思路:每次从当前元素的下一个开始计算sum,并把candidate加入List,并且跳过重复元素。
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]
题目大意:跟上一题类似,但是有点区别就是候选集中的元素只能出现一次。
解题思路:每次从当前元素的下一个开始计算sum,并把candidate加入List,并且跳过重复元素。
public List<List<Integer>> combinationSum2(int[] candidates, int target) { List<List<Integer>> res = new ArrayList<>(); if (candidates == null || candidates.length == 0) { return res; } Deque<Integer> tmp = new ArrayDeque<>(); Arrays.sort(candidates); helper(res, tmp, 0, target, candidates); return res; } private void helper(List<List<Integer>> res, Deque<Integer> tmp, int start, int target, int[] candidate) { if (target == 0) { res.add(new ArrayList<>(tmp)); // System.out.println(tmp); return; } for (int i = start; i < candidate.length && target >= candidate[i]; i++) { tmp.addLast(candidate[i]); helper(res, tmp, i + 1, target - candidate[i], candidate); tmp.removeLast(); while (i < candidate.length - 1 && candidate[i + 1] == candidate[i]) { i++; } } }
相关文章推荐
- (转)oracle表空间使用率统计查询
- 第二次冲刺06
- Java核心API -- 1(Object类)
- Yii2 - 数据库访问对象
- Dubbo实例
- Android NFC开发实战详解
- C#数据结构回顾之循环队列
- In-Call StatusBar 弹出时对界面的影响
- 微软100题(40)几道百度笔试题2
- oracle之报错:ORA-00054: 资源正忙,要求指定 NOWAIT
- Implement Trie (Prefix Tree)
- 在纵横比较中确定佳木斯人口方略
- 读陈毅同志《梅岭三章》
- 高性能网络编程2----TCP消息的发送
- Python实现控制台输入密码的方法
- 【1. 跳板机概述】云跳板机服务系统设计及实现
- UDP主要丢包原因及具体问题分析
- angularjs 和 ionic 教程网址
- sublime text2 nodejs插件安装
- (转)ORA-00257归档日志写满的解决方法