Climbing Stairs
70. Climbing Stairs
Difficulty: Easy
Related Topics: Math, Dynamic Programming, Memoization
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?
Example 1:
Input: n = 2 Output: 2 Explanation: There are two ways to climb to the top.
- 1 step + 1 step
- 2 steps
Example 2:
Input: n = 3 Output: 3 Explanation: There are three ways to climb to the top.
- 1 step + 1 step + 1 step
- 1 step + 2 steps
- 2 steps + 1 step
First Attempt:
Code:
class Solution:
def climbStairs(self, k: int) -> int:
def climb(k):
if k==0:
return 1
elif k==1:
return 2
else:
return climb(k-1) + climb((k-2))
return climb(k-1)
Feedback:
I found that this question is same as fibonacci numbers question, so I tried to use recursion to solve this problem, but it resulted time limit exit, because as number gets bigger, it recursively calls huge numbers of functions. I should use dynamic programming to solve this problem.
Second Attempt:
Code:
class Solution:
def climbStairs(self, k: int) -> int:
stairs = [0 for i in range(k)]
curr = 2
if k==1:
return 1
elif k==2:
return 2
else:
stairs[0] = 1
stairs[1] = 2
while curr < k:
stairs[curr] = stairs[curr-1] + stairs[curr-2]
curr+=1
return stairs[k-1]
Feedback:
I used dynamic programming to solve this time. I assigned a list with 0s for range of k. Then stored the values correctly using same logic to solve fibonacci numbers problem.