-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathdusunax.py
71 lines (52 loc) · 1.4 KB
/
dusunax.py
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
'''
# Leetcode 70. Climbing Stairs
use `dynamic programming` to solve the problem.
1. Bottom-up approach
2. Top-down approach
## Time and Space Complexity
### 1. Bottom-up approach
```
TC: O(n)
SC: O(1)
```
#### TC is O(n):
- iterating with a for loop. O(n)
#### SC is O(1):
- using a constant space to store the previous two steps. O(1)
### 2. Top-down approach
```
TC: O(n)
SC: O(n)
```
#### TC is O(n):
- performing a recursive call for each step. O(n)
#### SC is O(n):
- using a memoization object to store the previous two steps. O(n)
'''
class Solution:
'''
1. Bottom-up approach
'''
def climbStairsLoop(self, n: int) -> int:
if n == 1 or n == 2:
return n
# SC: O(1)
prev2 = 1 # ways to step 0
prev1 = 2 # ways to step 1
for i in range(3, n + 1): # TC: O(n)
current = prev1 + prev2 # ways to (n-1) + (n-2)
prev2 = prev1
prev1 = current
return prev1
'''
2. Top-down approach
'''
def climbStairsRecursive(self, n: int) -> int:
memo = {} # SC: O(n)
def dp(step: int, memo: int) -> int: # TC: O(n)
if step == 1 or step == 2:
memo[step] = step
if step not in memo:
memo[step] = dp(step - 1, memo) + dp(step - 2, memo) # ways to (n-1) + (n-2)
return memo[step]
return dp(n, memo)