Skip to content

Thinking recursively

Read · 1 of 3

Trust the smaller answer

Climbing n stairs, 1 or 2 at a time: your last move came from stair n − 1 or n − 2. So ways(n) = ways(n − 1) + ways(n − 2).

Written directly, it recomputes the same answers again and again. Saving each answer in a Map the first time makes it instant. That idea is dynamic programming.

JavaScript numbers are only exact up to about 9 × 10¹⁵. For bigger whole numbers use BigInt: write 1n, or BigInt(x), and print with String(x).

1const memo = new Map();
2function ways(n) {
3 if (n <= 2) return BigInt(n);
4 if (memo.has(n)) return memo.get(n);
5 const answer = ways(n - 1) + ways(n - 2);
6 memo.set(n, answer);
7 return answer;
8}