Star

LeetCode 39. Combination Sum

Question

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note: All numbers (including target) will be positive integers. The solution set must not contain duplicate combinations. For example, given candidate set [2, 3, 6, 7] and target 7, A solution set is:

1
2
3
4
[
[7],
[2, 2, 3]
]

Explanation

对于这类求所有组合的题目,必然用DFS来做。注意这里数字是可以重复用的,所以在helper递归的时候还用原来的index。

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
public class Solution {
public List<List<Integer>> combinationSum(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 (target < candidates[i]) {
break;
}
combination.add(candidates[i]);
helper(candidates, i, target - candidates[i], combination,list);
combination.remove(combination.size()-1);
}
}
}