Problem solution · Python

Paint House III

Paint House III: a Python solution using dynamic programming. Learn the idea, check the complexity, and read the full code, with credit to Kamyu LeetCode Solutions.

Technique
Dynamic programming
Source
Kamyu LeetCode Solutions
Length
53 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Dynamic programming

For Paint House III, the implementation records answers for smaller states and reuses them to build the requested result without repeating work.

  1. Define precisely what one DP state represents.
  2. Establish the base cases before transitions are evaluated.
  3. 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.

Source

Code and credit

This code comes from Kamyu LeetCode Solutions by kamyu104 and is used under the MIT licence.

Full codePaint House III · PythonPython
Use this to learn the idea, then write your own version.
# Time:  O(m * t * n^2)# Space: O(t * n) class Solution(object):    def minCost(self, houses, cost, m, n, target):        """        :type houses: List[int]        :type cost: List[List[int]]        :type m: int        :type n: int        :type target: int        :rtype: int        """        # dp[i][j][k]: cost of covering i+1 houses with j+1 neighbor groups and the (k+1)th color        dp = [[[float("inf") for _ in xrange(n)] for _ in xrange(target)] for _ in xrange(2)]        for i in xrange(m):            dp[i%2] = [[float("inf") for _ in xrange(n)] for _ in xrange(target)]            for j in xrange(min(target, i+1)):                for k in xrange(n):                    if houses[i] and houses[i]-1 != k:                        continue                    same = dp[(i-1)%2][j][k] if i-1 >= 0 else 0                    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 0                    paint = cost[i][k] if not houses[i] else 0                    dp[i%2][j][k] = min(same, diff)+paint        result = min(dp[(m-1)%2][-1])        return result if result != float("inf") else -1  # Time:  O(m * t * n^2)# Space: O(t * n)class Solution2(object):    def minCost(self, houses, cost, m, n, target):        """        :type houses: List[int]        :type cost: List[List[int]]        :type m: int        :type n: int        :type target: int        :rtype: int        """        dp = {(0, 0): 0}        for i, p in enumerate(houses):            new_dp = {}            for nk in (xrange(1, n+1) if not p else [p]):                for j, k in dp:                    nj = j + (k != nk)                    if nj > target:                        continue                    new_dp[nj, nk] = min(new_dp.get((nj, nk), float("inf")), dp[j, k] + (cost[i][nk-1] if nk != p else 0))            dp = new_dp        return min([dp[j, k] for j, k in dp if j == target] or [-1]) 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗