3.7.9 · D3Algorithm Paradigms

Worked examples — DP problems — Fibonacci, coin change (count + min), 0 - 1 knapsack

2,390 words11 min readBack to topic

The scenario matrix

Before working examples, let's list every distinct situation these four DP problems can hand you. Each row is a "case class"; the last column names the example that nails it.

# Case class What's special / where beginners break Covered by
A Fibonacci, ordinary build up from base — the "sticky note" walk Ex 1
B Fibonacci, degenerate recursion must stop before the recurrence Ex 1
C Coin count, reachable target dp[a]+=dp[a-c], coins outside Ex 2
D Coin count, target the "empty set" answer = 1, not 0 Ex 2
E Coin min, greedy would fail DP must beat greedy Ex 3
F Coin min, impossible target answer must be , not a wrong number Ex 4
G 0/1 knapsack, ordinary 2D table, look back to row Ex 5
H 0/1 knapsack, capacity 0 / item too heavy degenerate, nothing fits Ex 6
I 0/1 knapsack, 1D reverse-loop correctness the direction trap made concrete Ex 7
J Word problem (real world) translate a story into weights/values Ex 8
K Exam twist — count vs permutations loop-order changes the meaning Ex 9

We now walk one example per interesting cell. Read the Forecast first and actually guess — the learning happens in the gap between your guess and the truth.


Ex 1 — Fibonacci, ordinary + degenerate (cells A, B)


Ex 2 — Coin change count, reachable + zero target (cells C, D)


Ex 3 — Coin change min, greedy trap (cell E)


Ex 4 — Coin change min, impossible target (cell F)


Ex 5 — 0/1 knapsack, ordinary 2D (cell G)


Ex 6 — 0/1 knapsack, degenerate (zero capacity / item too heavy) (cell H)


Ex 7 — 0/1 knapsack, the 1D reverse-loop, made concrete (cell I)


Ex 8 — Word problem: the hiker's backpack (cell J)


Ex 9 — Exam twist: count vs permutations (loop order flips the meaning) (cell K)


Recall Self-test (reveal after answering)

Why does coin-change min return for coins=[2,4], amount=3? ::: All coins are even; an odd target is unreachable, so dp[3] stays and is converted to . In 1D 0/1 knapsack, which loop direction is correct and why? ::: Downward — it keeps dp[w-w_i] pointing at the state before the current item, enforcing "use each item at most once." What is dp[0] for coin-change count and why? ::: — there is exactly one way to make amount 0: the empty set. Same recurrence, coins-outside vs amount-outside gives what two meanings? ::: Coins outside = combinations (order ignored); amount outside = permutations (order counted).