-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathCombinationSumIII.java
More file actions
35 lines (30 loc) · 855 Bytes
/
CombinationSumIII.java
File metadata and controls
35 lines (30 loc) · 855 Bytes
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
/**
* LeetCode 216 https://leetcode.com/problems/combination-sum-iii/
*
*/
class Solution {
List<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backtrack(k, n, 1, 0);
return res;
}
void backtrack(int k, int n, int startIndex, int sum) {
// prune
if (n < sum) {
return;
}
//base case
if (path.size() == k && sum == n) {
res.add(new LinkedList(path));
return;
}
for (int i = startIndex; i <= 9 - (k - path.size()) + 1; i++) { // another prune
sum+= i;
path.add(i);
backtrack(k, n, i+1, sum);
sum-=i;
path.removeLast();
}
}
}