Lesson 2 · Unit 01
Define the state
Climbing stairs: state, recurrence, base cases
What you practise
- Climbing stairs: what f(n) means, the recurrence, the base cases
Try a question from this lesson
Pick one
ways(n) counts the climbs to stair n using moves of 1 or 2 stairs. Your last move was one of those two. So ways(n) equals…
Correct answer
ways(n - 1) + ways(n - 2)
Why
Every climb ends with a 1-move from stair n - 1 or a 2-move from stair n - 2. Those two groups share no climb and cover them all, so their counts add. Asking "what was the last move?" is how most recurrences are found.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
State, recurrence, base cases
Every DP solution has three parts.
The state: what a call means, in words. ways(n) is the number of ways to reach stair n.
The recurrence: how a state is built from smaller states.
The base cases: states small enough to answer directly. There is one way to stand on stair 0 (do nothing) and one way to reach stair 1.
def ways(n):
if n <= 1: # base cases
return 1
return ways(n - 1) + ways(n - 2)function ways(n) {
if (n <= 1) return 1; // base cases
return ways(n - 1) + ways(n - 2);
}function ways(n: number): number {
if (n <= 1) return 1; // base cases
return ways(n - 1) + ways(n - 2);
}Concept
Let the language memoize
Check, compute, store is so mechanical that you can wrap it around any function.
Python ships the wrapper as a decorator. JavaScript and TypeScript have none built in, so you keep a Map beside the function or write a small helper once.
from functools import cache
@cache
def ways(n):
if n <= 1:
return 1
return ways(n - 1) + ways(n - 2)
print(ways(50))function memoize(fn) {
const memo = new Map();
return (n) => {
if (!memo.has(n)) memo.set(n, fn(n));
return memo.get(n);
};
}
const ways = memoize((n) => {
if (n <= 1) return 1;
return ways(n - 1) + ways(n - 2);
});
console.log(ways(50));type Fn = (n: number) => number;
function memoize(fn: Fn): Fn {
const memo = new Map<number, number>();
return (n) => {
if (!memo.has(n)) memo.set(n, fn(n));
return memo.get(n)!;
};
}
const ways: Fn = memoize((n) => {
if (n <= 1) return 1;
return ways(n - 1) + ways(n - 2);
});
console.log(ways(50));Python note@cache (Python 3.9+) is lru_cache(maxsize=None). Arguments must be hashable, so pass tuples, not lists.
TypeScript notetype Fn names the function shape once. const ways: Fn must be annotated: a value that refers to itself in its own initializer cannot have its type inferred.
9 more exercises in the app
- 3× type the answer
- 1× fill the blanks
- 2× multiple choice
- 1× match the pairs
- 1× true or false
- 1× order the lines
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.