Skip to content

Instantly share code, notes, and snippets.

@ysinjab
Created November 18, 2022 08:14
Show Gist options
  • Save ysinjab/0eb14e595feb5ddaeaee3e5e357de1e1 to your computer and use it in GitHub Desktop.
Save ysinjab/0eb14e595feb5ddaeaee3e5e357de1e1 to your computer and use it in GitHub Desktop.
265. Paint House II
class Solution:
def minCostII(self, costs: List[List[int]]) -> int:
# Recursion or top-down approach
# state: at any given state returns the minimum cost of painting a house i
# with color k which is: costs[i][k] + minimum cost of painting a house i + 1 with not k
# state variables are:
# i house index
# k color for second house
# recurrence relation: dp(i, k) = costs[i][k] + min(dp(i+1))
# base case if i == len(costs) return 0
@lru_cache(None)
def dp(i, k):
if i == len(costs):
return 0
c = costs[i][k] + min([dp(i+1, color) for color, _ in enumerate(costs[i]) if color != k])
return c
return min([dp(0, color) for color, _ in enumerate(costs[0])])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment