Sub topic 7
Combinations and Target-Sum Search
This chapter assumes you know the choose-explore-unchoose template and the subsets generator from earlier chapters. It also assumes you are comfortable with Python lists and recursion.
A combination is a selection where order does not matter, so [2, 3] and [3, 2] count as the same answer. The subsets generator already handles this with a start index, which only lets the loop pick elements at or after the current position. Combinations problems keep that idea and add a stopping rule: a fixed size, or a target sum.
Fixed-Size Combinations
To choose k numbers from 1..n, record the path only when it reaches length k:
def combine(n, k):
result = []
path = []
def backtrack(start):
if len(path) == k:
result.append(path[:])
return
for i in range(start, n + 1):
path.append(i)
backtrack(i + 1)
path.pop()
backtrack(1)
return result
print(combine(4, 2))
# [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]Passing i + 1 means each number is used at most once, and every result comes out in increasing order. That ordering is how the code avoids producing duplicates.
Target-Sum Search with Reuse
In the target-sum problem, you find every combination of candidates that adds up to a target, and you may use each candidate more than once. The state you pass down is the remaining sum instead of a length.
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]]The recursive call passes i, not i + 1. The next level may pick the same candidate again, but it can never go back to an earlier one. That keeps reuse possible and still produces each multiset only once.
Choosing the Index You Pass Down
The argument you pass to the recursive call decides what kind of answers you get:
| Recursive call | Meaning | Typical problem |
|---|---|---|
| `backtrack(i + 1)` | Each element used at most once | Subsets, k-combinations |
| `backtrack(i)` | Reuse allowed, order ignored | Combination sum |
| `backtrack(0)` | Reuse allowed, order matters | Counting ordered sequences |
The break in the loop is a first example of pruning. The input is sorted, so once one candidate is larger than the remaining sum, every candidate after it is too. The next chapter covers pruning in general.
Exercise
Change combination_sum so that each candidate can be used at most once. Candidates are still distinct. What is the one-line change, and what does it return for candidates [2, 3, 5, 7] and target 10?
Show answer
Change the recursive call to backtrack(i + 1, remaining - c). The call returns [[2, 3, 5], [3, 7]].
Exercise
Why does combination_sum need the base case "remaining == 0" but no base case for "remaining < 0"?
Show answer
The loop breaks before appending any candidate larger than remaining, so remaining can never go negative. Without the sort and break, you would need an explicit check that returns when remaining < 0.