Sub topic 7
Combinations and Target-Sum Search
This chapter assumes you know the choose-explore-unchoose template, why results must be stored as copies (path[:]), and the subset generator from the previous chapters. The examples are in Python.
Subsets and permutations list everything. Most real tasks are narrower. You need groups of a fixed size, or groups whose values add up to a target. Both are combination problems: the order of the chosen items does not matter, so [2, 3] and [3, 2] count as the same answer. The subset generator already handles that. This chapter adds a stopping condition and decides whether an item can be picked more than once.
Combinations Are Subsets With a Stopping Rule
A k-combination is a subset of exactly k items. The subset generator records every node of its tree. A combination generator records only the nodes at depth k and stops going deeper once it reaches them.
def combine(n, k):
"""All k-element combinations of the numbers 1..n."""
result = []
path = []
def backtrack(start):
if len(path) == k:
result.append(path[:])
return
for x in range(start, n + 1):
path.append(x)
backtrack(x + 1)
path.pop()
backtrack(1)
return result
print(combine(4, 2))
# [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]The start parameter does the real work. Each call may only pick values larger than the last one picked, so every combination comes out in increasing order, and each one can be produced only one way. Without start, the search would also build [2, 1], [3, 1], and so on. Those are permutations, and they are duplicates for this problem.
Why the `start` index removes order
Think of start as a rule that the path must be non-decreasing in index. Any set of k items has exactly one arrangement that follows the rule, and that is its sorted order. Sorted order acts as the canonical form, and the tree contains one leaf per canonical form. This idea comes back whenever you need to avoid counting the same group twice.
Target-Sum Search With Reuse
The classic target-sum problem goes like this: given distinct positive integers and a target, find every combination that adds up to the target, where each candidate may be used any number of times. With [2, 3, 6, 7] and target 7, the answers are [2, 2, 3] and [7].
Instead of tracking path length, each call tracks the remaining sum. The call that reaches exactly zero records the path.
def combination_sum(candidates, target):
# Assumes candidates are distinct positive integers; each may be reused.
candidates = sorted(candidates)
result = []
path = []
def backtrack(start, remaining):
if remaining == 0:
result.append(path[:])
return
for i in range(start, len(candidates)):
c = candidates[i]
if c > remaining:
break # sorted input: every later candidate is too large too
path.append(c)
backtrack(i, remaining - c)
path.pop()
backtrack(0, target)
return result
print(combination_sum([2, 3, 6, 7], 7))
# [[2, 2, 3], [7]]There are two differences from combine.
- The recursive call passes
i, noti + 1. The same candidate stays available, so2can be chosen again. Candidates beforeiare still excluded, which keeps every path in non-decreasing order. - The input is sorted, so the loop can
breakat the first candidate bigger thanremaining. Every candidate after it is bigger too. This is a first look at pruning, which the next chapter covers in full.
The tree below shows the search for target 7. Each node shows the path and the remaining sum.
Look at [2, 3] with 2 remaining. Its loop starts at index 1, so the smallest candidate it may pick is 3, which is too large. A 2 would fit, but picking it would produce [2, 3, 2], a reordering of [2, 2, 3], which was already found. The start index rules it out.
Target-Sum Search Without Reuse
If each candidate may be used at most once, change one argument: recurse with i + 1.
def combination_sum_once(candidates, target):
# Assumes candidates are distinct positive integers; each used at most once.
candidates = sorted(candidates)
result = []
path = []
def backtrack(start, remaining):
if remaining == 0:
result.append(path[:])
return
for i in range(start, len(candidates)):
c = candidates[i]
if c > remaining:
break
path.append(c)
backtrack(i + 1, remaining - c)
path.pop()
backtrack(0, target)
return result
print(combination_sum_once([2, 3, 5, 6, 7], 7))
# [[2, 5], [7]]This version stops even without the size check, because start grows on every level and the loop eventually runs out of candidates. The reuse version depends on the remaining sum shrinking on every call, which is a stronger assumption.
Comparing the Variants
| Problem | Recursive call | Records a result when | Why the search stops |
|---|---|---|---|
| k-combinations of 1..n | `backtrack(x + 1)` | `len(path) == k` | Depth is capped at k |
| Target sum, reuse allowed | `backtrack(i, remaining - c)` | `remaining == 0` | `remaining` drops by at least the smallest candidate each level |
| Target sum, each used once | `backtrack(i + 1, remaining - c)` | `remaining == 0` | Index and sum both advance |
| Fixed size and target | `backtrack(i + 1, remaining - c)` | `len(path) == k and remaining == 0` | Depth cap and sum both apply |
You can combine these constraints freely. The base case checks every constraint that defines a finished answer. The loop and the recursive arguments decide which choices are still allowed.
Common Errors
Restarting the loop at zero
If you replace range(start, ...) with range(len(candidates)), the search generates ordered sequences instead of combinations:
def broken_combination_sum(candidates, target):
candidates = sorted(candidates)
result = []
path = []
def backtrack(remaining):
if remaining == 0:
result.append(path[:])
return
for c in candidates: # bug: ignores the start index
if c > remaining:
break
path.append(c)
backtrack(remaining - c)
path.pop()
backtrack(target)
return result
print(broken_combination_sum([2, 3, 6, 7], 7))
# [[2, 2, 3], [2, 3, 2], [3, 2, 2], [7]]Removing these duplicates after the fact by sorting each result and adding it to a set gives correct output. It still explores every ordering, though, which can be exponentially more work. Fix the generator instead.
Mixing up `i` and `i + 1`
Passing i + 1 when reuse is allowed silently loses answers such as [2, 2, 3]. Passing i when reuse is forbidden returns answers that use an item twice. Before you write the loop, decide which rule the problem uses.
Zero and negative candidates
The reuse version assumes every candidate is positive. A 0 lets the search pick it forever without remaining changing, so the recursion never ends (Python raises RecursionError). A negative candidate breaks the break pruning, because a larger sum could later shrink back to the target. With negatives allowed and reuse permitted, there can be infinitely many answers. Check the input at the boundary or reject such inputs explicitly.
Skipping `remaining < 0` checks without the break
If you drop the sorted-input break, you need some other guard, such as if remaining < 0: return at the top of backtrack. Without one, the reuse version recurses forever.
A Note on Cost
combine(n, k) produces C(n, k) results, and copying each one costs O(k), so the output alone takes O(k · C(n, k)) time. The tree also has internal nodes, but with the start index there are at most about as many of them as there are leaves for each depth. For target sum with reuse, the depth is at most target / min(candidates), which also bounds the extra space for the path and the call stack. The number of results can grow exponentially with the target, so no algorithm that lists them all can do better than exponential time in the worst case. The analysis chapter makes these bounds precise.
Exercise
Write combinationsum3(k, n) that returns every combination of exactly k distinct numbers from 1 to 9 that adds up to n. What does combinationsum3(3, 9) return?
Show answer
Use the no-reuse template over 1..9 and record only when len(path) == k and remaining == 0. You can also stop early when len(path) == k or x > remaining. One version: def combination_sum3(k, n): result, path = [], []; def bt(start, rem): if len(path) == k: if rem == 0: result.append(path[:]); return; for x in range(start, 10): if x > rem: break; path.append(x); bt(x + 1, rem - x); path.pop(). Then call bt(1, n) and return result. For (3, 9) it returns [[1, 2, 6], [1, 3, 5], [2, 3, 4]].
Exercise
In combination_sum([2, 3, 6, 7], 7), the call for path [2, 3] has remaining 2, and 2 is a candidate. Why does the search not produce [2, 3, 2]?
Show answer
That call's loop starts at the index of 3, so only 3, 6 and 7 can be picked, and 3 is already larger than 2, which triggers the break. Excluding earlier candidates keeps every path in non-decreasing order, and [2, 3, 2] would only repeat [2, 2, 3], which was already found.
Exercise
What happens if you call combination_sum([0, 2], 4), and how would you guard against it?
Show answer
The loop picks 0, recurses with remaining still 4, picks 0 again, and keeps going until Python raises RecursionError. Guard against it by rejecting non-positive candidates at the start, for example: if any(c <= 0 for c in candidates): raise ValueError("candidates must be positive").