Learn / Recursion and backtracking
Subsequences with sum
Is there a subsequence with sum k? How many are there? The take-or-skip recursion answers both by carrying the sum still needed. With positive values a negative remainder can stop a branch early, and when k is small a table of reachable sums answers the yes/no question in O(n × k).
How to recognise it
- The question asks whether some subset or subsequence adds up to a target, or how many do.
- Values are positive, or the target is small enough for a table indexed by sum.
The idea in one picture
Carry a counter of "how much is still needed". Taking a value lowers it; skipping leaves it. Reaching exactly 0 means the chosen values add up to the target.
Three versions of one question
| Question | Recursion returns | Combine branches with |
|---|---|---|
| Does one exist? | true or false | or (stop at the first true) |
| How many? | a count | + |
| With a small target | a table can[s] | can[s] = can[s] or can[s - v] |
Template: take or skip, carrying what is left
function count(i, left):
if left < 0: return 0 # positive values only
if i == n: return 1 if left == 0 else 0
return count(i + 1, left - a[i]) + count(i + 1, left)
Common mistakes
- Using the negative-remainder prune when values can be negative.
- Returning as soon as
left == 0when counting, which misses the same sum reached with extra zeros. - Counting the empty subsequence when the target is 0 and the question wants non-empty ones.
Problems
- Check if there exists a subsequence with sum Kmediumguide ready
- Count all subsequences with sum Kmediumguide ready
- Subset Sum Problemmediumguide ready