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 an array the first time (and reusing it after) makes it instant. That idea is dynamic programming.

1static long[] memo = new long[91];
2
3static long ways(int n) {
4 if (n <= 2) return n;
5 if (memo[n] != 0) return memo[n];
6 return memo[n] = ways(n - 1) + ways(n - 2);
7}