70. Climbing Stairs
Easy
Problem:
You are climbing a staircase. To reach the top, you must ascend n steps. If you can climb either 1 step or 2 steps at a time, calculate the number of distinct ways you can reach the top.
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
https://leetcode.com/problems/climbing-stairs/
Solution:
Fibonacci numbers
The method of solving this problem with memoization is similar to that of calculating Fibonacci numbers, with only a slight difference in the initial values.
class Solution:
dp = collections.defaultdict(int)
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
if self.dp[n]:
return self.dp[n]
self.dp[n] = self.climbStairs(n - 1) + self.climbStairs(n - 2)
return self.dp[n]
Reference: NeetCode
https://www.youtube.com/watch?v=Y0lT9Fck7qI
class Solution:
def climbStairs(self, n: int) -> int:
one, two = 1, 1
for i in range(n -1):
tmp = one
one = one + two
two = tmp
return one


Last updated