Climbing Stairs
Climbing Stairs is an easy 1-D Dynamic Programming problem from the Blind 75. The key pattern is 1-d dynamic programming, and a good solution runs in O(n) time.
Problem
Return the number of distinct ways to climb n steps using moves of one or two steps.
Examples
Example 1
Input
6Output
13Example 2
Input
2Output
2Example 3
Input
3Output
3Approach
The ways to reach a step are the ways to reach the step below plus the step two below, a Fibonacci recurrence kept in two variables.
| Pattern | 1-D dynamic programming |
|---|---|
| Time | O(n) |
| Space | O(1) |
Watch out for
Seed the recurrence correctly: one way for step 1, two ways for step 2.