-
Notifications
You must be signed in to change notification settings - Fork 16
/
CombinationSumIII.java
37 lines (32 loc) · 1.13 KB
/
CombinationSumIII.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
// https://leetcode.com/problems/combination-sum-iii
// T: O(9^k)
// S: O(k)
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class CombinationSumIII {
private final List<List<Integer>> result = new ArrayList<>();
private int sum;
public List<List<Integer>> combinationSum3(int k, int n) {
sum = n;
combinationSum(1, Math.min(sum / 2, 9), 0, k - 1, new LinkedList<>());
return result;
}
private void combinationSum(int start, int end, int currentSum, int k, LinkedList<Integer> current) {
if (k == 0) {
if (currentSum < sum && sum - currentSum >= start && sum - currentSum <= 9) {
current.add(sum - currentSum);
result.add(new ArrayList<>(current));
current.pollLast();
}
return;
}
for (int i = start ; i <= end ; i++) {
current.add(i);
currentSum += i;
combinationSum(i + 1, Math.min((sum - currentSum) / 2, 9), currentSum, k - 1, current);
currentSum -= i;
current.pollLast();
}
}
}