β All problems
#70Easyπ Pattern ???
Climbing Stairs
A staircase has n steps. Each move climbs either 1 or 2 steps. How many distinct ways are there to reach the top?
Try it on LeetCodeπ€ GUESS THE PATTERN+5 XP
Before you peek at the solution: which pattern do you think this one uses?
Hints0/3
Optional. Open them one at a time if you're stuck.
π¬ Walkthrough video

Video coming soon
The video is still being edited. Meanwhile, read the explanation and the code.
π Explanation
Intuition
To land on step n, your last move came either from n - 1 (a 1-step) or from n - 2 (a 2-step). So:
ways(n) = ways(n - 1) + ways(n - 2)
Plain recursion recomputes the same subproblems over and over, which takes O(2βΏ). Dynamic programming stores the results so you never compute twice.
Steps
- Base cases:
ways(1) = 1,ways(2) = 2. - Build bottom-up, keeping only the last two values
aandb. - Repeat
a, b = b, a + bforn - 1rounds.
Fun fact
The answers are the Fibonacci sequence shifted by one.
β±οΈ Complexity
TimeO(n)
SpaceO(1)
π» Solution code
class Solution:
def climbStairs(self, n: int) -> int:
a, b = 1, 1 # ways(0), ways(1)
for _ in range(n - 1):
a, b = b, a + b
return bGot it and submitted?
Mark it solved to earn XP and keep your streak alive.