|
1 | 1 | class Solution {
|
2 | 2 | public List<List<Integer>> combinationSum3(int k, int n) {
|
3 | 3 | List<List<Integer>> result = new ArrayList<>();
|
4 |
| - dfs(k, n, 1, new ArrayList<>(), result); |
| 4 | + helper(n, k, 1, new ArrayList<>(), result); |
5 | 5 | return result;
|
6 | 6 | }
|
7 | 7 |
|
8 |
| - private void dfs(int k, int n, int idx, List<Integer> tempResult, List<List<Integer>> result) { |
9 |
| - if (tempResult.size() == k && n == 0) { |
10 |
| - result.add(new ArrayList<>(tempResult)); |
| 8 | + private void helper(int n, int numsAllowed, int start, List<Integer> temp, List<List<Integer>> result) { |
| 9 | + if (numsAllowed == 0 && n == 0) { |
| 10 | + result.add(new ArrayList<>(temp)); |
11 | 11 | return;
|
12 | 12 | }
|
13 | 13 |
|
14 |
| - for (int i = idx; i <= 9; i++) { |
15 |
| - tempResult.add(i); |
16 |
| - dfs(k, n - i, i + 1, tempResult, result); |
17 |
| - tempResult.remove(tempResult.size() - 1); |
| 14 | + for (int i = start; i <= 9; i++) { |
| 15 | + temp.add(i); |
| 16 | + helper(n - i, numsAllowed - 1, i + 1, temp, result); |
| 17 | + temp.remove(temp.size() - 1); |
18 | 18 | }
|
19 | 19 | }
|
20 | 20 | }
|
0 commit comments