Combination Sum II
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 class Solution { public ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates, int target) { int len = candidates.length; ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>(); if(len == 0) return results; ArrayList<Integer> output = new ArrayList<Integer>(); Arrays.sort(candidates); int sum = 0, depth = 0; DFS(candidates, depth, sum, target, output, results); return results; } public void DFS(int[] candidates, int depth, int sum, int target, ArrayList<Integer> output, ArrayList<ArrayList<Integer>> results ){ if(sum > target) return; if(sum == target){ ArrayList<Integer> tmp = new ArrayList<Integer>(); tmp.addAll(output); results.add(tmp); return; } if(sum < target){ for(int i = depth; i < candidates.length; i++){ sum += candidates[i]; output.add(candidates[i]); DFS(candidates, i+1, sum, target, output, results); output.remove(output.size()-1); sum -= candidates[i]; while(i< candidates.length-1 && candidates[i] == candidates[i+1]) i++; } } } }