256. Paint House
题目:
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.
Note:
All costs are positive integers.
链接: http://leetcode.com/problems/paint-house/
3/4/2017
感觉每次做dp的题目想法都是对的,但是每次总想建立数组来存之前的值,可能是受算法导论里面的影响。其实如果中间值只是在下一次循环时候用到的话,完全可以用几个变量来表示,变量的数目就是本来要用数组的数目。
还是借鉴别人的不用数组的写法
1 public class Solution { 2 public int minCost(int[][] costs) { 3 if (costs == null || costs.length == 0) return 0; 4 5 int red = 0, blue = 0, green = 0; 6 for (int i = 0; i < costs.length; i++) { 7 int prevRed = red, prevBlue = blue, prevGreen = green; 8 red = costs[i][0] + Math.min(prevBlue, prevGreen); 9 blue = costs[i][1] + Math.min(prevRed, prevGreen); 10 green = costs[i][2] + Math.min(prevBlue, prevRed); 11 } 12 return Math.min(red, Math.min(blue, green)); 13 } 14 }