Skip to content

Commit 298d86e

Browse files
committed
combination sum III
1 parent 70e28c7 commit 298d86e

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package backtracking;
2+
3+
import java.util.ArrayList;
4+
import java.util.Arrays;
5+
import java.util.List;
6+
7+
// https://leetcode.com/problems/combination-sum-iii/
8+
public class CombinationSumIII {
9+
10+
public static void main(String[] args) {
11+
int k = 3;
12+
int n = 9;
13+
CombinationSumIII obj = new CombinationSumIII();
14+
List<List<Integer>> resultList = obj.combinationSum3(k ,n);
15+
System.out.println(Arrays.toString(resultList.toArray()));
16+
}
17+
18+
public List<List<Integer>> combinationSum3(int k, int n) {
19+
List<List<Integer>> resultList = new ArrayList<List<Integer>>();
20+
// dfs
21+
dfs(resultList, new ArrayList<Integer>(), k, n, 1);
22+
23+
return resultList;
24+
}
25+
26+
private void dfs(List<List<Integer>> resultList, List<Integer> list, int k, int sum, int start) {
27+
if (sum == 0 && k == 0) {
28+
resultList.add(new ArrayList<Integer>(list));
29+
return;
30+
}
31+
if (sum < 0 || start > 9) {
32+
return;
33+
}
34+
for (int i = start; i <= 9; i++) {
35+
// add num
36+
list.add(i);
37+
dfs(resultList, list, k - 1, sum - i, i + 1);
38+
39+
// not add num
40+
list.remove(list.size() - 1);
41+
}
42+
}
43+
44+
}

0 commit comments

Comments
 (0)