Count the ways up a staircase taking one or two steps at a time. Each stair's count is the sum of the two below it, so climb once and keep just two numbers.
▼The problem
LeetCode 70 (Easy). You climb a staircase of n steps, taking 1 or 2 steps at a time. How many distinct ways reach the top?
Example: n = 5 → 8 ways (11111, 221, 122, 1112, 1121, 1211, 2111, 212; the three narrated ones first).
def climb_stairs(n):
a, b = 1, 1 # ground, stair 1
for _ in range(n - 1):
a, b = b, a + b
return bTRY IT ON LEETCODE ▶The solution
def climb_stairs(n):
a, b = 1, 1 # ground, stair 1
for _ in range(n - 1):
a, b = b, a + b
return bTranscript
Climbing Stairs. You're climbing a staircase with n steps. Each move, you climb either one step or two. How many different ways can you reach the top?
Take five stairs. You could go one step at a time. Or two, two, one. Or one, two, two. Order matters, so those last two are different climbs. Count every mix of ones and twos, and there are eight ways.
The direct way starts from the last move. To stand on stair n, you came from one stair below, or from two below. So the ways to reach n are the ways to reach n minus one, plus the ways to reach n minus two.
As plain recursion, that's slow: it solves the same stairs again and again. For five stairs, stair three is solved twice and stair two three times. For forty stairs, that's over three hundred million calls.
Instead, build up from the bottom. Each stair's count is the sum of the two stairs below it, worked out once and written down. That's the Fibonacci sequence. And since each stair looks only two stairs down, you only need to keep the last two numbers.
Let's climb. The ground has one way: stand still. Stair one: one way. Stair two: one plus one, two. Stair three: two plus one, three. Stair four: three plus two, five. Stair five: five plus three, eight. Eight ways to the top, the same eight we counted by hand.
In code, two variables hold the ways to the last two stairs. Both start at one: the ground and stair one. Each loop climbs one stair: the new count is their sum, and the older one drops away. After n minus one loops, the newer one is the answer.
Each stair costs one addition, so the time is linear: forty stairs take thirty-nine additions, not three hundred million calls. And the space is constant: just two numbers, however tall the staircase.
Add the two stairs below, and keep climbing. That's Climbing Stairs.