-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCombinationSum3.java
More file actions
41 lines (36 loc) · 1.12 KB
/
CombinationSum3.java
File metadata and controls
41 lines (36 loc) · 1.12 KB
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
39
40
41
package com.leetcode.backtracking;
import java.util.ArrayList;
import java.util.List;
/**
* @author: yhl
* @DateTime: 2021/2/27 0:04
* @Description: 组合总和 III
*/
public class CombinationSum3 {
public static void main(String[] args) {
CombinationSum3 combinationSum3 = new CombinationSum3();
List<List<Integer>> res = combinationSum3.combinationSum3(9, 45);
System.out.println(res);
}
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res = new ArrayList<>();
if (k == 0 || n == 0) {
return res;
}
List<Integer> path = new ArrayList<>();
dfs(k, n, 1, res, path);
return res;
}
// 1-9 k个数的和为n的组合
private void dfs(int k, int n, int begin, List<List<Integer>> res, List<Integer> path) {
if (path.size() == k && 0 == n) {
res.add(new ArrayList<>(path));
return;
}
for (int i = begin; i <= 9; i++) {
path.add(i);
dfs(k, n - i, i + 1, res, path);
path.remove(path.size() - 1);
}
}
}