Subset Sum visualization

Find a subset adding up to a target by deciding include/exclude for each item.

Explore a binary decision tree: for item i, first try including it, then try excluding it. Undo choices on the way back up.

Edge case: the common "stop when the sum exceeds the target" pruning is only valid when all numbers are non-negative. With negative numbers a later item can bring the sum back down, so pruning is disabled automatically.

Complexity

Time: best O(n), average O(2ⁿ), worst O(2ⁿ). Space: O(n). Difficulty: Intermediate.

Pseudocode

procedure search(i, sum):
  if sum = target and chosen non-empty: return true
  if i = n: return false
  if allNonNegative and sum > target: return false   // prune
  choose A[i]; if search(i+1, sum + A[i]): return true
  unchoose A[i]
  return search(i+1, sum)                     // skip A[i]

More backtracking algorithms