There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. 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 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on... Find the minimum cost to paint all houses.
1 用动态规划来实现,如果dp[i][j]表示给第i+1个房子刷颜色j,则上一个房子肯定是刷颜色j+1或者是j+2,即dp[i-1][j+1]或者dp[i-1][j+2],所以dp[i][j]=min(dp[i-1][j+1], dp[i-1][j+2])+dp[i][j]
2 注意当涂第i+1个房子的时候,会有三种选择,基于这三种选择中的任何一个,前面都有涂另外两种颜色的最小cost。比如当前房子想涂红色,那当前房子涂红色的最小cost=min(pre涂蓝色最小cost,pre涂绿色最小cost)+ 当前涂红色cost
3 也就是说对于第一所房子来说,我们有三种选择,将有三种cost,到第二所房子的时候,我们也会有三种选择:
第二所涂红色,cost = min(第一所涂蓝色cost,第一所涂绿色cost)+ 第二所涂红色cost
第二所涂蓝色,cost = min(第一所涂红色cost,第一所涂绿色cost)+ 第二所涂蓝色cost
第二所涂绿色,cost = min(第一所涂红色cost,第一所涂蓝色cost)+ 第二所涂绿色cost
4 依次下去,到最后一所房子的时候,有三种选择,然后有三个cost,选择最小cost的那个颜色
5 pre = costs[0][:]是指把costs的第一排的值全部复制到pre中
6 now =[0]*3代表初始化一个list,[0,0,0]
7 更新的时候,一个一个更新now[0], now[1], now[2]
必须要有tmp变量
1 思路是对于当前house,paint红色的话,那就从上一个房子喷蓝色和绿色中选cost小的那个方案,然后加上当前cost;同理,paint蓝色的话,就从上一个房子喷红色和绿色中选cost小的那个方案,然后加上当前cost;......
2 所以对于当前房子,喷红色,蓝色和绿色,分别有各自的最小cost的方案组合,就这样一直更新,直到最后一个房子,在红色,蓝色和绿色三种方案中再找到最小cost那个方案就是所得