Topic:
There is a row of n houses, each house can is painted with one of the three colors:red, blue or green. The cost of painting a certain color is different. You had to paint all the houses such, that no, and adjacent houses have the same color.
The cost of painting a certain color was represented by a cost n x 3
matrix. For example, was the cost of costs[0][0]
painting House 0 with color red; costs[1][2]
the cost of Painting House 1 with color green, And so on ... Find the minimum cost-to-paint all houses.
Note:
All costs is positive integers.
Links: http://leetcode.com/problems/paint-house/
Exercises
The house is painted with RGB paint, each paint for each house is not the same cost, requires two adjacent houses not a color, and the least cost. This problem to see the hint need to do with DP. At first I want to set a sum, a last color =-1, but there is no way to solve the problem of duplicate. So I still refer to the code of the Jianchao.li, the RGB respectively DP.
Time Complexity-o (n), Space complexity-o (1)
Public classSolution { Public intMincost (int[] costs) {//DP if(Costs = =NULL|| Costs.length = = 0) { return0; } intLen = costs.length, red = 0, blue = 0, green = 0; for(inti = 0; i < costs.length; i++) { intprevred = red, Prevblue = blue, Prevgreen =Green; Red= Costs[i][0] +math.min (Prevblue, Prevgreen); Blue= Costs[i][1] +math.min (prevred, Prevgreen); Green= Costs[i][2] +math.min (prevred, Prevblue); } returnmath.min (Red, math.min (blue, green)); }}
Reference:
The "Paint House"