265. Paint House II
Problem description:
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 an n x k
cost matrix costs.
- For example,
costs[0][0]
is the cost of painting house0
with color0
;costs[1][2]
is the cost of painting house1
with color2
, and so on…
Return the minimum cost to paint all houses.
Example 1:
1 | Input: costs = [[1,5,3],[2,9,4]] |
Example 2:
1 | Input: costs = [[1,3],[2,4]] |
Constraints:
costs.length == n
costs[i].length == k
1 <= n <= 100
1 <= k <= 20
1 <= costs[i][j] <= 20
Solution:
Update the whole array. Find two smallest elements, min1
min2
, in previous row costs[i-1]
.
Then when we update every column in row cost[i-1]
.
If index is the same as previous row’s smallest element, then we use min2 instead.
1 | class Solution: |
time complexity: $O(nk)$
space complexity: $O(1)$
reference:
related problem: