CODE 93: Combination Sum II
来源:互联网 发布:婚纱p图软件 编辑:程序博客网 时间:2024/04/29 23:45
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]
public ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates,int target) {// IMPORTANT: Please reset any member data you declared, as// the same Solution instance will be reused for each test case.Arrays.sort(candidates);return dfs(candidates, target, 0, 0);}ArrayList<ArrayList<Integer>> dfs(int[] candidates, int target, int sum,int i) {if (i >= candidates.length) {ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();return results;}ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();for (int index = 0; index * candidates[i] <= target && index <= 1; index++) {int tmpsum = sum + index * candidates[i];if (tmpsum == target) {ArrayList<Integer> result = new ArrayList<Integer>();for (int m = 0; m < index; m++) {result.add(0, candidates[i]);}if (!results.contains(result)) {results.add(result);}} else if (tmpsum < target) {ArrayList<ArrayList<Integer>> tmpResults = dfs(candidates,target, tmpsum, i + 1);for (ArrayList<Integer> tmpResult : tmpResults) {ArrayList<Integer> newResult = new ArrayList<Integer>();newResult.addAll(tmpResult);for (int m = 0; m < index; m++) {newResult.add(0, candidates[i]);}if (!results.contains(newResult)) {results.add(newResult);}}}}return results;}
- CODE 93: Combination Sum II
- Combination Sum && Combination Sum II
- Combination Sum Combination Sum II
- CODE 94: Combination Sum
- [leet code] Combination Sum
- Combination Sum II
- LeetCode: Combination Sum II
- LeetCode: Combination Sum II
- [LeetCode]Combination Sum II
- LeetCode Combination Sum II
- [Leetcode] Combination Sum II
- Combination Sum II
- [LeetCode] Combination Sum II
- LeetCode Combination Sum II
- [Leetcode] Combination Sum II
- Combination Sum II
- LeetCode: Combination Sum II
- Combination Sum II
- 数据包的游走
- sql表的管理-sql学习笔记3
- AWK 简明教程
- Java中StringTokenizer的使用
- 0026算法笔记——【贪心算法】多机调度问题
- CODE 93: Combination Sum II
- JBoss 系列三十三:jBPM5示例之 HelloWorld
- 电工学 学习总结一
- 0025算法笔记——【贪心算法】最小生成树问题
- Android多渠道打包解决方案(兰贝壳儿)
- STL 中优先队列,队列以及statck的使用方法(priority_queu)
- 0024算法笔记——【贪心算法】单源最短路径问题
- Flex模块化开发优势及技巧解析
- JBoss 系列三十四:jBPM5示例之 Looping