70. Climbing Stairs
You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Approach: DP (O(n) Space)
Let dp[i] represents the number of ways to climb the stairs.
The recurrence relation is: dp[i] = dp[i-1] + dp[i-2]
Similar to the fibonacci problem, to reach step i:
- Come from step i-1 with a 1-step move
- Come from step i-2 with a 2-step move
So the number of ways to reach step n is the sum of the ways to reach steps i-1 and i-2.
class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
dp = [0] * (n+1)
dp[1], dp[2] = 1, 2
for i in range(3, n+1):
dp[i] = dp[i-1] + dp[i-2]
return dp[n]- Time: — we iterate through the array once.
- Space: — we use an array of size to store the intermediate results.
Last updated on