-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0216CombinationSumiii.java
More file actions
38 lines (30 loc) · 990 Bytes
/
_0216CombinationSumiii.java
File metadata and controls
38 lines (30 loc) · 990 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
36
37
38
package com.heatwave.leetcode.problems;
import java.util.ArrayList;
import java.util.List;
public class _0216CombinationSumiii {
static class Solution {
List<Integer> temp = new ArrayList<>();
int tempSum = 0;
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backtracking(1, 9, k, n);
return ans;
}
private void backtracking(int start, int end, int k, int n) {
if (temp.size() > k || tempSum > n) {
return;
}
if (temp.size() == k && tempSum == n) {
ans.add(new ArrayList<>(temp));
return;
}
for (int i = start; i <= end; i++) {
temp.add(i);
tempSum += i;
backtracking(i + 1, end, k, n);
temp.remove(temp.size() - 1);
tempSum -= i;
}
}
}
}