-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution216.java
50 lines (43 loc) · 1.37 KB
/
Solution216.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.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* @author: mayuan
* @desc: 组合总和 III
* @date: 2018/08/12
*/
public class Solution216 {
public static void main(String[] args) {
Solution216 test = new Solution216();
List<List<Integer>> result = test.combinationSum3(3, 7);
result.forEach(list -> {
for (int n : list) {
System.out.print(n);
System.out.print(" ");
}
System.out.println();
});
}
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> answer = new LinkedList<>();
List<Integer> oneAnswer = new ArrayList<>(k);
dfs(answer, oneAnswer, k, n, 1);
return answer;
}
private void dfs(List<List<Integer>> answer, List<Integer> oneAnswer, int size, int targetSum, int startNumber) {
if (0 > targetSum) {
return;
}
if (oneAnswer.size() == size && 0 == targetSum) {
answer.add(new ArrayList<>(oneAnswer));
return;
}
// 依次迭代每个数字 1~9
for (int num = startNumber; num <= 9; ++num) {
oneAnswer.add(num);
dfs(answer, oneAnswer, size, targetSum - num, num + 1);
oneAnswer.remove(oneAnswer.size() - 1);
}
}
}