Module 28
DP Foundations: 1D
Dynamic programming from scratch: memoisation, tabulation, the five-step recipe, take-or-skip decisions, and the classic 1D problems.
Dynamic programming (DP) is recursion that remembers. When a recursive solution keeps solving the same smaller problems again and again, storing each answer the first time turns an exponential algorithm into a linear one.
This module builds the habit step by step. You'll see the waste in plain recursion, fix it with memoisation, rewrite it bottom-up as a table, shrink the table to a few variables, and then use one recipe (state, transition, base cases, order, answer) on the classic 1D problems: stairs, robbers, decodings, word breaks and products.
Best after: Recursion
Part 1
Learn the ideas
- 28.1From Recursion to MemoisationIf a recursive function is called with the same arguments many times, cache each result the first time it's computed. The work drops to (number of distinct states) × (work per state).14 min
- 28.2Tabulation and the Five-Step RecipeBottom-up DP fills a table from the smallest states upward. Write down state, transition, base cases, order and answer before coding.14 min
- 28.3Take-or-Skip DecisionsMany 1D problems ask, at each item, whether to use it. dp[i] = best of (skip item i) and (take item i plus the best compatible earlier state).12 min
- 28.4Recognising a DP ProblemCount the ways, find the min or max, or decide yes or no over choices that interact, especially when greedy fails and brute force branches exponentially.8 min
Part 2
Solve the problems
In order of difficulty. Each one shows the pattern it teaches.
The first DP: ways(i) = ways(i − 1) + ways(i − 2).
Switching from counting to minimising: same shape, min instead of +.
Take-or-skip: dp[i] = max(dp[i − 1], dp[i − 2] + nums[i]).
Break a circle into two lines: exclude the first house or exclude the last.
Transforming a problem into House Robber by bucketing values.
Counting with validity checks: one-digit and two-digit transitions, careful with zeros.
A yes/no DP over prefixes: can the first i characters be split into dictionary words?
Carrying two states: a negative number turns the smallest product into the largest.