Climbing Stairs
Examples
Example 1:
Input: n = 2
Output: 2
Explanation:
Example 2:
Input: n = 3
Output: 3
Explanation:
Example 1:
Input: n = 2
Output: 2
Explanation:
Example 2:
Input: n = 3
Output: 3
Explanation:
You are given an integer n representing the number of steps to reach the top of a staircase. You can climb with either 1 or 2 steps at a time.
Return the number of distinct ways to climb to the top of the staircase.
1 + 1 = 22 = 21 + 1 + 1 = 31 + 2 = 32 + 1 = 31 <= n <= 30This is the Fibonacci sequence: to reach step i, you can come from i-1 or i-2. Track only the last two values and iterate up to n.
Every valid way to reach step i ends with a jump from i-1 or i-2, so the total ways are the sum of those two subproblems. Iterating computes these values in order.
O(n)O(1)class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
prev2, prev1 = 1, 2
for _ in range(3, n + 1):
prev2, prev1 = prev1, prev1 + prev2
return prev1