Star

LeetCode 40. 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. 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
2
3
4
5
6
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]

Explanation

其实相比1还要简单一些。用DFS找到所有的组合,注意去重。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> list = new ArrayList<>();
if (candidates == null || candidates.length == 0) return list;
Arrays.sort(candidates);
helper(candidates, 0, target, new ArrayList<Integer>(), list);
return list;
}
// 在list[index:]中选取和为target的所有组合,添加到combination之后,整个放到combinations当中
public void helper(int[] candidates, int startIndex, int target, List<Integer> combination, List<List<Integer>> list) {
if (target == 0) list.add(new ArrayList<Integer>(combination));
for(int i=startIndex; i< candidates.length; i++) {
if (i >startIndex && candidates[i] == candidates[i-1]) continue; //去重的重要步骤,因为数列是升序。
if (target < candidates[i]) {
break;
}
combination.add(candidates[i]);
helper(candidates, i+1, target - candidates[i], combination,list);
combination.remove(combination.size()-1);
}
}
}