Dynamic programming stores solutions to overlapping subproblems so that the same work is not repeated. The difficult design step is deciding what each stored value means.
Worked example
For the number of ways to climb n steps when each move takes one or two steps, define ways[i] as the number of valid sequences that reach step i. The last move comes from i minus one or i minus two, so add those two counts. Setting ways[0] to one represents the one empty sequence, and ways[1] is one.
What to check
Check that the cases cover every possibility without counting any sequence twice. The recurrence computes n states in linear time. Because each state needs only the previous two values, storage can be reduced to constant space when the full history is unnecessary. For large n, the count can exceed fixed-width integer limits. The recurrence and the chosen numeric representation both belong in the correctness argument.
Continue with the book
Explore the full treatment, worked examples, and exercises in Algorithms Made Simple.
Companion article for Algorithms Made Simple, published by Choral Software. Article text and original examples © 2026 Choral Software. All rights reserved.
