/ Data Structure and Algorithms  

Leetcode 216. Combination Sum III

Question



k represents the number that can be selected for each combination, n represents the target sum, the selectable numbers are 1 to 9, each number in each combination can only be selected once. Return all combinations that add up up to n.

Similar Questions

Solution

A very typical backtracking or DFS problem. Consider all situations, and then determine in turn.

The backtracking method can be regarded as a template. The overall framework is a larger for loop, then add first, then use recursion to traverse, then remove and continue the loop.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> result = new ArrayList<>();

getResult(result, new ArrayList<>(), k, n, 1);

return result;
}

private void getResult(List<List<Integer>> result, List<Integer> temp, int k, int n, int start) {
// if reach the length and remaining is 0
if (temp.size() == k) {
if (n == 0) {
result.add(new ArrayList<>(temp));
}

return;
}

for (int i = start; i < 10; i++) {
temp.add(i);
getResult(result, temp, k, n - i, i + 1);
temp.remove(temp.size() - 1);
}
}