-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathSolution039.java
50 lines (42 loc) · 1.49 KB
/
Solution039.java
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package algorithm.leetcode;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
/**
* @author: mayuan
* @desc: 组合总和
* @date: 2018/07/31
*/
public class Solution039 {
public static void main(String[] args) {
Solution039 test = new Solution039();
List<List<Integer>> ans = test.combinationSum(new int[]{2, 3, 6, 7}, 7);
ans.forEach(System.out::println);
ans = test.combinationSum(new int[]{2, 3, 5}, 8);
ans.forEach(System.out::println);
}
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> answer = new LinkedList<>();
List<Integer> oneAnswer = new LinkedList<>();
if (null == candidates || 0 >= candidates.length || 0 >= target) {
return answer;
}
// 必须先进行排序
Arrays.sort(candidates);
dfs(candidates, target, answer, oneAnswer, 0);
return answer;
}
public void dfs(int[] candidates, int target, List<List<Integer>> answer, List<Integer> oneAnswer, int start) {
if (0 > target) {
return;
} else if (0 == target) {
answer.add(new LinkedList<>(oneAnswer));
} else {
for (int i = start; i < candidates.length; ++i) {
oneAnswer.add(candidates[i]);
dfs(candidates, target - candidates[i], answer, oneAnswer, i);
oneAnswer.remove(oneAnswer.size() - 1);
}
}
}
}