- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 53 lines of Python from the credited upstream file paint-house-iii.py.
- The implementation visibly relies on sequence storage, cached states.
- No explicit loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 4class Solution(object):5 def minCost(self, houses, cost, m, n, target):6 """7 :type houses: List[int]8 :type cost: List[List[int]]9 :type m: int10 :type n: int11 :type target: int12 :rtype: int13 """14 15 dp = [[[float("inf") for _ in xrange(n)] for _ in xrange(target)] for _ in xrange(2)]16 for i in xrange(m):17 dp[i%2] = [[float("inf") for _ in xrange(n)] for _ in xrange(target)]18 for j in xrange(min(target, i+1)):19 for k in xrange(n):20 if houses[i] and houses[i]-1 != k:21 continue22 same = dp[(i-1)%2][j][k] if i-1 >= 0 else 023 diff = (min([dp[(i-1)%2][j-1][nk] for nk in xrange(n) if nk != k] or [float("inf")]) if j-1 >= 0 else float("inf")) if i-1 >= 0 else 024 paint = cost[i][k] if not houses[i] else 025 dp[i%2][j][k] = min(same, diff)+paint26 result = min(dp[(m-1)%2][-1])27 return result if result != float("inf") else -128 29 303132class Solution2(object):33 def minCost(self, houses, cost, m, n, target):34 """35 :type houses: List[int]36 :type cost: List[List[int]]37 :type m: int38 :type n: int39 :type target: int40 :rtype: int41 """42 dp = {(0, 0): 0}43 for i, p in enumerate(houses):44 new_dp = {}45 for nk in (xrange(1, n+1) if not p else [p]):46 for j, k in dp:47 nj = j + (k != nk)48 if nj > target:49 continue50 new_dp[nj, nk] = min(new_dp.get((nj, nk), float("inf")), dp[j, k] + (cost[i][nk-1] if nk != p else 0))51 dp = new_dp52 return min([dp[j, k] for j, k in dp if j == target] or [-1])53