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

QuestionRecursion returnsCombine branches with
Does one exist?true or falseor (stop at the first true)
How many?a count+
With a small targeta 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 == 0 when 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

0 of 3 solved

Check yourself

With positive values, why can a branch stop as soon as the remaining sum is negative?

To count subsequences with sum k, what do the two branches return together?

In the table version, why loop s from k down to the value v?