Combination Sum III
Problem
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Example 1:
Input: k = 3, n = 7
Output:
[[1,2,4]]
Example 2:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
Solution
Typical Backtracking Solution
public class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res = new ArrayList<>();
helper(res, new ArrayList<>(), 1, k, n);
return res;
}
private void helper(List<List<Integer>> res, List<Integer> list, int start, int k, int n) {
if (list.size() == k && n == 0) {
res.add(new ArrayList<>(list));
return;
}
for (int i = start; i <= 9; i++) {
list.add(i);
helper(res, list, i + 1, k, n - i);
list.remove(list.size() - 1);
}
}
}
Analysis
Typical backtracking solution
In the helper()
method, we have a for
loop starting from start
until the 9
as problem required
Notice that we only add current list
to our res
if list.size() == k && n == 0