1. Title
Combination Sum II
2. Http address
https://leetcode.com/problems/combination-sum-ii/
3. The question
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]
4. My code(AC)
1 //Accepted 2 public List<List<Integer>> combinationSum2(int[] candidates, int target) { 3 4 List<List<Integer>> result = new ArrayList<List<Integer>>(); 5 if( candidates == null) 6 return result; 7 8 int len = candidates.length; 9 int sum = 0; 10 List<Integer> subList = new ArrayList<Integer>(); 11 Arrays.sort(candidates); 12 for(int i = 0 ; i < len; i++) 13 { 14 sum = candidates[i]; 15 subList.add(candidates[i]); 16 getCombinationSum(candidates, i + 1, sum ,target,subList, result); 17 sum = 0; 18 subList.remove(0); 19 } 20 return result; 21 } 22 private void getCombinationSum(int[] candidates, int begin, int sum, 23 int target, List<Integer> subList, List<List<Integer>> result) { 24 25 if( sum > target) 26 { 27 return; 28 } 29 if( sum == target) 30 { 31 List<Integer> add = new ArrayList<Integer>(subList); 32 if( !result.contains(add)) 33 result.add(new ArrayList<Integer>(subList)); 34 return; 35 } 36 37 int len = candidates.length; 38 for(int i = begin; i < len; i++) 39 { 40 sum += candidates[i]; 41 subList.add(candidates[i]); 42 getCombinationSum(candidates, i + 1, sum, target, subList, result); 43 subList.remove(subList.size() -1); 44 sum -= candidates[i]; 45 } 46 }