Home
DSA Patterns
Backtracking
Combination Sum III
Combination Sum III (LeetCode 216)
Combination Sum III (LeetCode 216): find every set of k different digits from 1 to 9 that adds up to n. Backtrack over the digits in increasing order and stop a branch as soon as the next digit is larger than what remains.
Problem Understanding
Combination Sum III (LeetCode 216): find all valid combinations of k numbers that sum up to n, using only the digits 1 to 9, each at most once. Return them in any order, with no combination listed twice.
Examples: k = 3, n = 7 → [[1,2,4]]; k = 3, n = 9 → [[1,2,6],[1,3,5],[2,3,4]]; k = 4, n = 1 → [].
The Intuition: Choose, Explore, Un-choose
Build a path of digits one at a time, always larger than the last, and undo each choice after exploring it.
backtrack(start, remaining)tries every digitdfromstartto 9.- Stop early: if
d > remaining, no digit from here on fits, so break. - Choose
d, recurse withd + 1andremaining − d, then un-choose it. - Base case: when the path holds
kdigits, it is an answer ifremainingis 0. Either way, stop going deeper.
This is the backtracking template from Combinations and Combination Sum II, with a fixed pool of nine digits.
Combination Sum III Visualization
k = 3 DIGITS · SUM n = 9 · EACH DIGIT AT MOST ONCE
backtrack(1, n)
digits
path · 0 of k = 3
EMPTY
remaining
9
found
0
combinations
None yet
Choose 3 different digits from 1 to 9, in increasing order, that add up to 9
Next
Take 1: path [1], 8 remaining
k
n
The top row is the digits 1 to 9; digits on the current path are outlined, and a digit that stops the loop for being too large turns red. The path itself is underneath, green when it is recorded. Change k and n, and try k = 2, n = 10, where 5 + 5 is not allowed.
Combination Sum III Dry Run
Input: k = 3, n = 9. The first answers, in the order the search finds them:
| Path | Remaining | What happens |
|---|---|---|
| [1, 2, 3] | 3 | 3 digits but 3 left: dead end |
| [1, 2, 4], [1, 2, 5] | 2, 1 | dead ends |
| [1, 2, 6] | 0 | record |
| [1, 2] + 7 | 7 > 6 remaining: break | |
| [1, 3, 4] | 1 | dead end |
| [1, 3, 5] | 0 | record |
| [1, 4] + 5 | 5 > 4 remaining: break | |
| [2, 3, 4] | 0 | record |
Every later path breaks before it reaches three digits.
Answer: [[1,2,6],[1,3,5],[2,3,4]].
Combination Sum III LeetCode Solution
The choose, explore, un-choose loop with a count check and an early break.
Combination Sum III Code
1var combinationSum3 = function(k, n) {2 const result = [], path = [];3 const backtrack = (start, remaining) => {4 if (path.length === k) {5 if (remaining === 0) {6 result.push([...path]);7 }8 return;9 }10 for (let d = start; d <= 9; d++) {11 if (d > remaining) {12 break;13 }14 path.push(d);15 backtrack(d + 1, remaining - d);16 path.pop();17 }18 };19 backtrack(1, n);20 return result;21};
Combination Sum III in Python, Java, C++, TypeScript and C
Combination Sum III in Python
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
result, path = [], []
def backtrack(start, remaining):
if len(path) == k:
if remaining == 0:
result.append(path[:])
return
for d in range(start, 10):
if d > remaining:
break
path.append(d)
backtrack(d + 1, remaining - d)
path.pop()
backtrack(1, n)
return resultCombination Sum III in Java
class Solution {
private final List<List<Integer>> result = new ArrayList<>();
private final List<Integer> path = new ArrayList<>();
public List<List<Integer>> combinationSum3(int k, int n) {
backtrack(1, n, k);
return result;
}
private void backtrack(int start, int remaining, int k) {
if (path.size() == k) {
if (remaining == 0) {
result.add(new ArrayList<>(path));
}
return;
}
for (int d = start; d <= 9; d++) {
if (d > remaining) {
break;
}
path.add(d);
backtrack(d + 1, remaining - d, k);
path.remove(path.size() - 1);
}
}
}Combination Sum III in C++
class Solution {
vector<vector<int>> result;
vector<int> path;
void backtrack(int start, int remaining, int k) {
if ((int)path.size() == k) {
if (remaining == 0) {
result.push_back(path);
}
return;
}
for (int d = start; d <= 9; d++) {
if (d > remaining) {
break;
}
path.push_back(d);
backtrack(d + 1, remaining - d, k);
path.pop_back();
}
}
public:
vector<vector<int>> combinationSum3(int k, int n) {
backtrack(1, n, k);
return result;
}
};Combination Sum III in TypeScript
function combinationSum3(k: number, n: number): number[][] {
const result: number[][] = [], path: number[] = [];
const backtrack = (start: number, remaining: number): void => {
if (path.length === k) {
if (remaining === 0) {
result.push([...path]);
}
return;
}
for (let d = start; d <= 9; d++) {
if (d > remaining) {
break;
}
path.push(d);
backtrack(d + 1, remaining - d);
path.pop();
}
};
backtrack(1, n);
return result;
}Combination Sum III in C
static int** result;
static int count, path[9], depth;
static void backtrack(int start, int remaining, int k) {
if (depth == k) {
if (remaining == 0) {
result[count] = malloc(k * sizeof(int));
memcpy(result[count++], path, k * sizeof(int));
}
return;
}
for (int d = start; d <= 9; d++) {
if (d > remaining) {
break;
}
path[depth++] = d;
backtrack(d + 1, remaining - d, k);
depth--;
}
}
int** combinationSum3(int k, int n, int* returnSize, int** returnColumnSizes) {
result = malloc(126 * sizeof(int*)); /* C(9, 4) = 126 is the most there can be */
count = 0;
depth = 0;
backtrack(1, n, k);
*returnSize = count;
*returnColumnSizes = malloc((count > 0 ? count : 1) * sizeof(int));
for (int i = 0; i < count; i++) {
(*returnColumnSizes)[i] = k;
}
return result;
}Edge Cases & Common Mistakes
- Starting the next digit at 1 instead of d + 1: paths repeat in different orders and digits get reused.
- Recording when the sum matches but the count does not: an answer needs exactly k digits.
- Appending the path itself: later changes would alter the stored answer; append a copy.
- n too small or too large: with k = 4, n = 1 or n = 50 there is no answer, and the result is empty.
Summary
Backtrack over the digits 1 to 9 in increasing order, record a path of k digits whose sum is n, and break as soon as a digit is larger than what remains. At most C(9, k) answers, O(k) extra space for the path.
More practice: DSA interview questions with answers · patterns cheat sheet
