Combination Sum II 解答
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]
Solution 1 -- DFS
Similar solution as Combination Sum.
1 public class Solution { 2 public List<List<Integer>> combinationSum2(int[] candidates, int target) { 3 Arrays.sort(candidates); 4 List<List<Integer>> result = new ArrayList<List<Integer>>(); 5 for (int i = 0; i < candidates.length; i++) { 6 List<Integer> record = new ArrayList<Integer>(); 7 record.add(candidates[i]); 8 dfs(candidates, i, target - candidates[i], result, record); 9 } 10 return result; 11 } 12 private void dfs(int[] candidates, int start, int target, List<List<Integer>> result, List<Integer> record) { 13 if (target < 0) 14 return; 15 if (target == 0) { 16 if (!result.contains(record)) 17 result.add(new ArrayList<Integer>(record)); 18 return; 19 } 20 // Because C can only be used once, we start from "start + 1" 21 for(int i = start + 1; i < candidates.length; i++) { 22 record.add(candidates[i]); 23 dfs(candidates, i, target - candidates[i], result, record); 24 record.remove(record.size() - 1); 25 } 26 } 27 }
Solution 2 -- BFS
To avoid duplicates in array, we can create a class:
class Node {
public int val;
public int index;
}
And put these node in arraylists for BFS.