Skip to content

Commit 27cfff9

Browse files
authored
Create Min Cost Climbing Stairs - Leetcode 746.py
1 parent 58cedd8 commit 27cfff9

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
class Solution:
2+
def minCostClimbingStairs(self, cost: List[int]) -> int:
3+
# Recursive Solution
4+
n = len(cost)
5+
6+
def min_cost(i):
7+
if i < 2:
8+
return 0
9+
10+
return min(cost[i-2] + min_cost(i-2),
11+
cost[i-1] + min_cost(i-1))
12+
13+
return min_cost(n)
14+
# Time: O(2^n)
15+
# Space: O(n)
16+
17+
18+
class Solution:
19+
def minCostClimbingStairs(self, cost: List[int]) -> int:
20+
# Top Down DP (Memoization)
21+
n = len(cost)
22+
memo = {0:0, 1:0}
23+
def min_cost(i):
24+
if i in memo:
25+
return memo[i]
26+
else:
27+
memo[i] = min(cost[i-2] + min_cost(i-2),
28+
cost[i-1] + min_cost(i-1))
29+
return memo[i]
30+
31+
return min_cost(n)
32+
# Time: O(n)
33+
# Space: O(n)
34+
35+
36+
class Solution:
37+
def minCostClimbingStairs(self, cost: List[int]) -> int:
38+
# Bottom Up DP (Tabulation)
39+
n = len(cost)
40+
dp = [0] * (n+1)
41+
42+
for i in range(2, n+1):
43+
dp[i] = min(dp[i-2] + cost[i-2], dp[i-1] + cost[i-1])
44+
45+
return dp[-1]
46+
47+
# Time: O(n)
48+
# Space: O(n)
49+
50+
51+
class Solution:
52+
def minCostClimbingStairs(self, cost: List[int]) -> int:
53+
# Bottom Up DP (Constant Space)
54+
n = len(cost)
55+
prev, curr = 0, 0
56+
57+
for i in range(2, n+1):
58+
prev, curr = curr, min(cost[i-2] + prev, cost[i-1] + curr)
59+
60+
return curr
61+
62+
# Time: O(n)
63+
# Space: O(1)
64+

0 commit comments

Comments
 (0)