Skip to content

Commit 1a555d6

Browse files
committed
add solution: climbing-stairs
1 parent 6693c07 commit 1a555d6

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

climbing-stairs/dusunax.py

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
'''
2+
# Leetcode 70. Climbing Stairs
3+
4+
use `dynamic programming` to solve the problem.
5+
6+
1. Bottom-up approach
7+
2. Top-down approach
8+
9+
## Time and Space Complexity
10+
11+
### 1. Bottom-up approach
12+
13+
```
14+
TC: O(n)
15+
SC: O(1)
16+
```
17+
18+
#### TC is O(n):
19+
- iterating with a for loop. O(n)
20+
21+
#### SC is O(1):
22+
- using a constant space to store the previous two steps. O(1)
23+
24+
### 2. Top-down approach
25+
26+
```
27+
TC: O(n)
28+
SC: O(n)
29+
```
30+
31+
#### TC is O(n):
32+
- performing a recursive call for each step. O(n)
33+
34+
#### SC is O(n):
35+
- using a memoization object to store the previous two steps. O(n)
36+
'''
37+
38+
class Solution:
39+
'''
40+
1. Bottom-up approach
41+
'''
42+
def climbStairsLoop(self, n: int) -> int:
43+
if n == 1 or n == 2:
44+
return n
45+
46+
# SC: O(1)
47+
prev2 = 1 # ways to step 0
48+
prev1 = 1 # ways to step 1
49+
50+
for i in range(3, n + 1): # TC: O(n)
51+
current = prev1 + prev2 # ways to (n-1) + (n-2)
52+
prev2 = prev1
53+
prev1 = current
54+
55+
return prev1
56+
57+
'''
58+
2. Top-down approach
59+
'''
60+
def climbStairsRecursive(self, n: int) -> int:
61+
memo = {} # SC: O(n)
62+
63+
def dp(step: int, memo: int) -> int: # TC: O(n)
64+
if step == 1 or step == 2:
65+
memo[step] = step
66+
if step not in memo:
67+
memo[step] = dp(step - 1, memo) + dp(step - 2, memo) # ways to (n-1) + (n-2)
68+
return memo[step]
69+
70+
return dp(n, memo)
71+

0 commit comments

Comments
 (0)