-
Notifications
You must be signed in to change notification settings - Fork 29
/
Solution216.java
35 lines (25 loc) · 949 Bytes
/
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
package backstracking_problem;
import java.util.ArrayList;
import java.util.List;
public class Solution216 {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> combinations = new ArrayList<>();
List<Integer> tempCombination = new ArrayList<>();
backtracking(k, n, 1, tempCombination, combinations);
return combinations;
}
private void backtracking(int k, int n, int start, List<Integer> tempCombination, List<List<Integer>> combinations) {
if (k == 0 && n == 0) {
combinations.add(new ArrayList<>(tempCombination));
return;
}
if (k == 0 || n == 0) {
return;
}
for (int i = start; i <= 9; i++) {
tempCombination.add(i);
backtracking(k - 1, n - i, i + 1, tempCombination, combinations);
tempCombination.remove(tempCombination.size() - 1);
}
}
}