Problem overview
The method climbStairs receives the number of steps n and returns in how many distinct ways you can climb them, taking 1 or 2 steps at a time. Order counts: 1 step then 2 steps is a different way from 2 steps then 1 step. The constraints are 1 <= n <= 45, and the answer always fits in a 32-bit integer.
For n = 4 the answer is 5: 1+1+1+1, 1+1+2, 1+2+1, 2+1+1 and 2+2. For n = 3 it is 3, and for n = 2 it is 2.
Approach: build the counts from the bottom up
Think about the very last move onto step k. It was either a 1-step move from step k - 1 or a 2-step move from step k - 2. These end differently, so they are different ways, and nothing is counted twice. Therefore:
ways(k) = ways(k - 1) + ways(k - 2)
This is the pattern of dynamic programming: a big answer is built from the answers to smaller versions of the same question. A direct recursive function would recompute the same values again and again and take exponential time. Counting from step 2 upward computes each value once.
Each value depends only on the two before it, so the code doesn't need a whole table. Two variables are enough: prev for the step two below and curr for the step one below. The starting values are both 1. Step 0, the ground, counts as one way (don't move), and step 1 has one way (a single 1-step move). Counting the ground as 1 is what makes step 2 come out as 1 + 1 = 2.
Here is the loop for n = 5, copied from a real run:
| Step | ways | prev after | curr after |
|---|---|---|---|
| 2 | 2 | 1 | 2 |
| 3 | 3 | 2 | 3 |
| 4 | 5 | 3 | 5 |
| 5 | 8 | 5 | 8 |
After the last round curr is 8, so there are 8 ways to climb 5 steps. The sequence 1, 2, 3, 5, 8 is the Fibonacci sequence.
Step by step
- Create
prevwithvar, set to 1. It holds the ways to stand on step 0. It usesvarbecause the loop will change it. - Create
currthe same way, also 1. It holds the ways to reach step 1. Forn = 1the loop does nothing andcurris already right. - Loop over steps 2 up to
n. The range2..<(n + 1)covers exactly those steps. The body never uses the step number, so the loop variable is_. Write the closing brace right away. - Add the two counts into a
letconstant namedways. It is the number of ways to reach the step this round is counting. It never changes after that, soletfits. - Slide the window up one step. Set
prevtocurrfirst, thencurrtoways. With the opposite order,currwould be overwritten beforeprevcould copy it. - Return
currafter the loop. It holds the count for stepn.
The solution in Swift
class Solution {
func climbStairs(_ n: Int) -> Int {
var prev = 1
var curr = 1
for _ in 2..<(n + 1) {
let ways = prev + curr
prev = curr
curr = ways
}
return curr
}
}
The Swift details worth a closer look:
- Half-open ranges.
2..<(n + 1)stops beforen + 1, so the last value isn. The parentheses make the arithmetic happen first, and the range stays readable. The closed form2...nwould be the same range forn = 2or more. - Ranges can't run backwards. Building a range whose end is below its start stops the program with a run-time error. The half-open
2..<2is a valid empty range, which is whyn = 1works: the range is2..<2and the body never runs. With2...nandn = 1the range would be2...1, which is invalid. The same crash happens forn = 0, which is outside the constraints. for _ in. When the loop variable isn't used, the underscore says so, and the compiler doesn't warn about an unused name.letinside the loop. A newwaysconstant is created each round.prevandcurrlive outside the loop and are declared withvar, so the loop can assign to them.- Overflow traps. A Swift
Intis 64 bits, and overflowing it crashes the program instead of wrapping. Here the values stay small: forn = 45the result is 1836311903.
Complexity
Time: O(n). The loop runs n - 1 times and each round does a constant amount of work.
Space: O(1). Only prev, curr and ways are stored, however large n is.
Edge cases and common mistakes
n = 1. The loop is skipped and the method returns 1.- Starting
prevat 0. Then step 2 would come out as 1, not 2. The ground counts as one way. - Updating in the wrong order. Writing
curr = waysbeforeprev = currmakes both variables equal toways, and every later sum is wrong. - Using
2...n. It crashes forn = 1, as explained above. - Plain recursion.
climbStairs(n - 1) + climbStairs(n - 2)is correct but recomputes values and becomes far too slow nearn = 45.
Testing
Try these in the editor above. The results come from running the reference solution:
n = 1gives1.n = 2gives2.n = 3gives3.n = 4gives5.n = 10gives89.n = 45gives1836311903.
