265. Paint House II
LeetCode 265. Paint House II
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:
Example 2:
Constraints:
costs.length == n
costs[i].length == k
1 <= n <= 100
1 <= k <= 20
1 <= costs[i][j] <= 20
Follow up: Could you solve it in O(nk)
runtime?
Tags
Dynamic Programming
Solution
The basic idea is inherited from LeetCode 256. Paint House. However, when we need to calculate the minimum number for each cur[i], the time overhead would be O(k²)
. To save it from repeated minimum value computing, we obtain the the two smallest numbers in pre
before we update cur
. Let's say that the minimum value of pre
is first
and its index is i
, and the last but one minimum number is called second
. We can find that all elements apart from cur[i]
share the same minimum value first
, and the minimum value in terms of cur[i]
is second
. In this way, we manage to optimize the time complexity from O(nk²)
to O(nk)
.
Complexity
Time complexity:
Space complexity:
Code
Last updated
Was this helpful?