Combination Sum III
Input: k = 3, n = 7
Output: [[1,2,4]]Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]Solution
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> ans = new ArrayList<>();
comboHelper(1, n, k, new ArrayList<Integer>(), ans);
return ans;
}
private void comboHelper(int start, int remain, int k, List<Integer> combo, List<List<Integer>> ans) {
if (remain == 0) {
if (combo.size() == k) {
ans.add(new ArrayList<Integer>(combo));
}
return;
}
for (int i = start; i <= 9; i++) {
combo.add(i);
comboHelper(i + 1, remain - i, k, combo, ans);
combo.remove(combo.size() - 1);
}
}
}Reference
Last updated