Skip to content
Open

DP-2 #1790

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions coinChange2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Time Complexity : O(n * amount)
# Space Complexity : O(n * amount)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach:
# Use 2D DP Count ways to make each amount using available coins.
# For every coin, either don’t use it or use it (can reuse many times).

class Solution:
def change(self, amount: int, coins: List[int]) -> int:
dp = [[0 for i in range(amount + 1)] for j in range(len(coins) + 1)]

for i in range(len(coins) + 1):
dp[i][0] = 1

for i in range(1, len(coins) + 1):
for j in range(amount + 1):
if j < coins[i - 1]:
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = dp[i - 1][j] + dp[i][j - coins[i - 1]]

return dp[len(coins)][amount]
19 changes: 19 additions & 0 deletions paintHouse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Time Complexity : O(n)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach: Start from the last house. For each house, add its cost to the minimum of the other two colors.
# Return the minimum final cost.

class Solution:
def minCost(self, costs):
if not costs:
return 0
r, g, b = costs[-1]
for i in range(len(costs) - 2, -1, -1):
nr = costs[i][0] + min(g, b)
ng = costs[i][1] + min(r, b)
nb = costs[i][2] + min(r, g)
r, g, b = nr, ng, nb

return min(r, g, b)