# 265. Paint House II
There are a row of n houses, each house can be painted with one of the k colors. The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color.
The cost of painting each house with a certain color is represented by a n x k
cost matrix. For example, costs[0][0]
is the cost of painting house 0 with color 0; costs[1][2]
is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.
Note: All costs are positive integers.
Follow up:
Could you solve it in O(nk)
runtime?
# Solution
Approach 1: DP. For an O(nk)
solution, record the minimum cost, second to minimum cost and the index of the minimum cost for each house.
# Code (Python) (not yet verified on leetcode)
Approach 1:
def min_cost_paint(costs): # n * k cost matrix, where n is the number of houses, and k is the number of colors
# costs[h][c] -- total costs up to house h if h is colored with c. Need costs[houses-1] across all c's.
houses, colors = len(costs), len(costs[0])
minimum, second_minimum, minimum_index = 0, 0, -1
for h in range(houses):
new_minimum, new_second_minimum, new_minimum_index = float('inf'), float('inf'), -1
for c in range(colors):
# add the minimum cost if painting a different color, otherwise add the second minimum cost
total_cost = costs[h][c] + (minimum if c != minimum_index else second_minimum)
if total_cost <= new_minimum:
new_minimum, new_second_minimum, new_minimum_index = total_cost, new_minimum, c
elif total_cost <= new_second_minimum:
new_second_minimum = total_cost
minimum, second_minimum, minimum_index = new_minimum, new_second_minimum, new_minimum_index
return minimum
# Code (C++)
Approach 1:
Approach 2: