Browse curriculum

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.

  1. backtrack(start, remaining) tries every digit d from start to 9.
  2. Stop early: if d > remaining, no digit from here on fits, so break.
  3. Choose d, recurse with d + 1 and remaining − d, then un-choose it.
  4. Base case: when the path holds k digits, it is an answer if remaining is 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

1
2
3
4
5
6
7
8
9

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

Free preview: the first 30 of 97 steps

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 result
Combination 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

The approach, step by step

  1. Start

    Call backtrack(1, n) with an empty path.

  2. Base case

    When the path holds k digits, record it if nothing remains, and return either way.

  3. Try each digit

    For d from start to 9: break if d > remaining; otherwise add d, recurse with d + 1 and remaining − d, then remove d.

Frequently asked questions

Why pick the digits in increasing order?

A combination is a set, so [1, 2, 6] and [6, 2, 1] are the same answer. Building each path in increasing order, with the next digit starting just above the last one, produces every set exactly once and also guarantees no digit is used twice.


Why can the loop break instead of continue when d > remaining?

The digits are tried in increasing order, so if d is already larger than the sum still needed, every later digit is larger too. None of them can fit, so the whole rest of the loop is skipped with one break.


How is this different from Combination Sum and Combination Sum II?

Combination Sum reuses candidates any number of times, and Combination Sum II uses each candidate once but must skip duplicates in the input. Here the candidates are fixed, the digits 1 to 9 with no duplicates, and the answer must have exactly k numbers, so the base case checks the count as well as the sum.


How many combinations can there be?

At most C(9, k), the number of ways to choose k digits from 9; the largest is C(9, 4) = C(9, 5) = 126. That bounds both the answers and the work, which is why the search is fast even though it tries every possibility.

New to the technique behind this problem? Watch it run step by step:

Backtracking Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description