Combination Sum II 解答

时间:2022-09-11 05:54:27

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.

 public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<List<Integer>>();
for (int i = 0; i < candidates.length; i++) {
List<Integer> record = new ArrayList<Integer>();
record.add(candidates[i]);
dfs(candidates, i, target - candidates[i], result, record);
}
return result;
}
private void dfs(int[] candidates, int start, int target, List<List<Integer>> result, List<Integer> record) {
if (target < 0)
return;
if (target == 0) {
if (!result.contains(record))
result.add(new ArrayList<Integer>(record));
return;
}
// Because C can only be used once, we start from "start + 1"
for(int i = start + 1; i < candidates.length; i++) {
record.add(candidates[i]);
dfs(candidates, i, target - candidates[i], result, record);
record.remove(record.size() - 1);
}
}
}

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.