Climbing stairs with a memo
Standard · Write code · about 10 min
A staircase has n steps. Each move climbs 1 step or 2 steps. Return the number of different move sequences that reach the top.
Write it as a recursive function with a memo. The last move was either 1 step or 2 steps, so ways(n) = ways(n - 1) + ways(n - 2).
Example 1
Input:
[3]
Output:
3
Example 2
Input:
[2]
Output:
2
1 + 1, or 2.
Constraints
- 1 ≤ n ≤ 45
- The answer fits in a 32-bit signed integer
Learn the idea first: Overlapping subproblems and memoization, a visual lesson.
More Overlapping subproblems and memoization problems
- Memoized Fibonacci Warm-up
- Calls with and without memo Warm-up
- Which calls hit the cache Standard
- Fewest steps to one Standard
- Memoized grid paths Challenge