-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclimb_stairs.py
More file actions
27 lines (21 loc) · 834 Bytes
/
climb_stairs.py
File metadata and controls
27 lines (21 loc) · 834 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution:
def climbStairs(self, n: int) -> int:
"""
Tabulation:
- Depends on the base solution that is being set
- Solved in the direction of solving the base cases to the main problem
Intuition:
- To reach step i, look back at how to go there in one move.
- Either came from one step before or two steps before.
- Summing those possibilities covers all ways to get to i.
"""
if n == 0 or n == 1:
return 1
dp = [0] * (n + 1)
dp[0] = 1 # how many ways to reach step 0? 1 way: do nothing
dp[1] = 1 # how many ways to reach step 1? 1 way: 1 step
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
# Time Complexity: O(n)
# Space Complexity: O(n)