You are climbing a staircase that takes n steps to reach the top. Each time you can either climb 1 or 2 steps. Return the number of distinct ways you can climb to the top.
- Constraints:
1 <= n <= 45 - Example:
Input: n = 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
Solution
Approach
- Dynamic Programming / Fibonacci Sequence: Notice that to reach step
n, you must come from either stepn-1(taking 1 step) or stepn-2(taking 2 steps). - State Transition:
ways(n) = ways(n-1) + ways(n-2)with base casesways(1) = 1andways(2) = 2. - Space Optimization: Instead of an array, use two variables to track the previous two values, achieving
O(n)time complexity andO(1)space.
def climbStairs(n: int) -> int:
if n <= 2:
return n
a, b = 1, 2
for _ in range(3, n + 1):
a, b = b, a + b
return b