Created
November 18, 2022 08:14
-
-
Save ysinjab/0eb14e595feb5ddaeaee3e5e357de1e1 to your computer and use it in GitHub Desktop.
265. Paint House II
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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