216. Combination Sum III
Problem
Return every combination of k distinct numbers from 1–9 that adds up to n, each number used at most once.
Example: k = 3, n = 9 → [[1,2,6],[1,3,5],[2,3,4]]
Choose k distinct digits from 1–9 summing to n: combinations with i + 1 and pruning when the remainder goes negative.
Complexity: O(C(9, k)).
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
res, path = [], []
def bt(start, rest):
if len(path) == k:
if rest == 0:
res.append(path[:])
return
for d in range(start, 10):
if d > rest:
break
path.append(d)
bt(d + 1, rest - d)
path.pop()
bt(1, n)
return res
assert sorted(map(sorted, Solution().combinationSum3(3, 7))) == sorted(map(sorted, [[1, 2, 4]]))
assert sorted(map(sorted, Solution().combinationSum3(3, 9))) == sorted(map(sorted, [[1, 2, 6], [1, 3, 5], [2, 3, 4]]))
assert sorted(map(sorted, Solution().combinationSum3(4, 1))) == sorted(map(sorted, []))
class Solution {
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> res = new ArrayList<>();
bt(k, 1, n, new ArrayList<>(), res);
return res;
}
private void bt(int k, int start, int rest, List<Integer> path, List<List<Integer>> res) {
if (path.size() == k) { if (rest == 0) res.add(new ArrayList<>(path)); return; }
for (int d = start; d <= 9 && d <= rest; d++) {
path.add(d);
bt(k, d + 1, rest - d, path, res);
path.remove(path.size() - 1);
}
}
}
func combinationSum3(k int, n int) [][]int {
res, path := [][]int{}, []int{}
var bt func(start, rest int)
bt = func(start, rest int) {
if len(path) == k {
if rest == 0 {
res = append(res, append([]int{}, path...))
}
return
}
for d := start; d <= 9 && d <= rest; d++ {
path = append(path, d)
bt(d+1, rest-d)
path = path[:len(path)-1]
}
}
bt(1, n)
return res
}