Combination Sum III (LeetCode 216): Solution and Explanation
Find every set of exactly k distinct digits from 1 through 9 whose values add up to n. Each digit can appear at most once in a combination, and the order of digits inside a combination does not matter, so [1,2,4] and [4,2,1] count as the same answer.
Watch it run step by step
Try your own input and write the code →Intuition
Because the pool of candidates is tiny, the brute force is genuinely possible: there are only 2⁹ = 512 subsets of the digits 1 through 9. You could enumerate every subset, keep those with exactly k elements and the right sum, and return them. That is already fast, so the real lesson here is how to structure the search cleanly so it scales to the harder members of the combination family.
The standard structure is backtracking with a start index. You build a combination one digit at a time, and each recursive call only considers digits larger than the last one you picked. That single rule removes duplicates like [2,1,4] versus [1,2,4] for free, because every combination is generated in increasing order exactly once.
The other ingredient is pruning. You carry the remaining sum down the recursion, and you stop a branch as soon as it has k digits or the remaining sum goes negative. A branch that already holds k digits can only succeed if the remaining sum is exactly zero, so that check doubles as the success condition.
Approach: Backtracking with a start index
- Create an empty
resultlist and a recursive helperbacktrack(start, path, remaining). - If
pathhaskdigits andremainingis 0, append a copy ofpathtoresultand return. - If
pathalready haskor more digits, orremainingis negative, return, because this branch cannot produce a valid answer. - Otherwise loop
ifromstartto 9. Appendi, recurse withstart = i + 1andremaining - i, then popito undo the choice. - Kick off the search with
backtrack(1, [], n)and returnresult.
Step-by-step example
k = 3, n = 7
- The search starts with
path = []andremaining = 7. It picks 1, leaving 6, then picks 2, leaving 4. - With [1,2] it tries 3: the path [1,2,3] has three digits but 1 is left over, so that branch returns without recording anything.
- Next it tries 4: [1,2,4] has three digits and
remainingis exactly 0, so a copy is added toresult. - Trying 5 through 9 after [1,2] drives
remainingnegative, so each of those calls returns immediately. - Branches such as [1,3], [1,4] and [2,3] cannot be completed: [1,3,4] needs 8 and [2,3,4] needs 9, both above 7. The final answer is [[1,2,4]].
Code: Python, Java, C++
1class Solution:
2 def combinationSum3(self, k: int, n: int) -> List[List[int]]:
3 result = []
4
5 def backtrack(start, path, remaining):
6 if len(path) == k and remaining == 0:
7 result.append(path[:])
8 return
9 if len(path) >= k or remaining < 0:
10 return
11
12 for i in range(start, 10):
13 path.append(i)
14 backtrack(i + 1, path, remaining - i)
15 path.pop()
16
17 backtrack(1, [], n)
18 return result1class Solution {
2 public List<List<Integer>> combinationSum3(int k, int n) {
3 List<List<Integer>> result = new ArrayList<>();
4 backtrack(1, new ArrayList<>(), n, k, result);
5 return result;
6 }
7
8 private void backtrack(int start, List<Integer> path, int remaining, int k, List<List<Integer>> result) {
9 if (path.size() == k && remaining == 0) {
10 result.add(new ArrayList<>(path));
11 return;
12 }
13 if (path.size() >= k || remaining < 0) return;
14
15 for (int i = start; i <= 9; i++) {
16 path.add(i);
17 backtrack(i + 1, path, remaining - i, k, result);
18 path.remove(path.size() - 1);
19 }
20 }
21}1class Solution {
2public:
3 vector<vector<int>> combinationSum3(int k, int n) {
4 vector<vector<int>> result;
5 vector<int> path;
6 backtrack(1, path, n, k, result);
7 return result;
8 }
9
10 void backtrack(int start, vector<int>& path, int remaining, int k, vector<vector<int>>& result) {
11 if (path.size() == k && remaining == 0) {
12 result.push_back(path);
13 return;
14 }
15 if (path.size() >= k || remaining < 0) return;
16
17 for (int i = start; i <= 9; i++) {
18 path.push_back(i);
19 backtrack(i + 1, path, remaining - i, k, result);
20 path.pop_back();
21 }
22 }
23};Time and space complexity
O(C(9, k) × k)
The recursion only ever explores increasing sequences of distinct digits, so it visits at most the 512 subsets of 1 through 9, and each recorded answer costs O(k) to copy. In practice this is bounded by a small constant because the digit pool never grows.
O(k)
The recursion depth and the working path never exceed k digits, which is at most 9. The output list is not counted as extra space.
Other approaches
Bitmask enumeration (time O(2⁹ × 9), space O(1))
Loop over every mask from 0 to 511, keep masks with exactly k set bits whose digit sum equals n, and convert them to lists. It has no recursion and is easy to get right, but it always checks all 512 masks with no pruning.
Common mistakes
- Reusing digits. Recursing with
start = iinstead ofi + 1lets the same digit appear twice, which this problem forbids. - Appending
pathitself instead of a copy. Every entry inresultthen points at the same list and ends up empty after backtracking undoes the choices. - Looping up to
range(start, 9)and silently excluding the digit 9. The upper bound must be 10 in Python. - Not pruning on a negative remainder. The code still works without it, but the search then wanders through many hopeless branches; breaking out of the loop once
i > remainingis an easy extra speedup.
Frequently asked questions
What is the difference between Combination Sum, II and III?
The first lets you reuse each candidate any number of times, the second gives a list with duplicates where each element is used once, and the third fixes the pool to the digits 1 through 9 and also fixes the combination size to k. All three use the same backtracking skeleton with small changes to the start index and duplicate handling.
What is the time complexity of Combination Sum III?
It is bounded by the number of subsets of nine digits, so at most 512 search states plus O(k) per recorded answer. That makes it effectively constant time, which is why the constraints are so relaxed.
Why don't I need a visited set to avoid duplicate combinations?
Each call only considers digits larger than the last one chosen, so every combination is built in strictly increasing order. A given set of digits has exactly one increasing order, so it can only be generated once.
What happens when n is larger than 45?
The largest possible sum uses all nine digits and equals 45, so any larger n has no solution and the function returns an empty list after a short search.