216. Combination Sum III (Medium)
https://leetcode.com/problems/combination-sum-iii/
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.
Note:
- All numbers will be positive integers.
- The solution set must not contain duplicate combinations.
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]]
Solutions
class Solution {
// Search all the possible combinations as searching the binary tree, cut the branches if necessary.
public List<List<Integer>> combinationSum3(int k, int n) {
if (k <= 0) {
return new LinkedList<>();
}
List<List<Integer>> ans = new LinkedList<>();
recurse(1, n, k, new LinkedList<>(), ans);
return ans;
}
private void recurse(int start, int remainTarget, int k, LinkedList<Integer> track, List<List<Integer>> ans) {
if (track.size() == k && remainTarget == 0) {
ans.add(new LinkedList<>(track));
return;
}
// Since each element can be only used once, the loop should begin from index start
for (int i = start; i <= 9; i++) {
if (i > remainTarget) {
break;
}
track.add(i);
recurse(i + 1, remainTarget - i, k, track, ans);
track.removeLast();
}
}
}