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.
一刷
题解:
刚开始还是没有思路解决duplicate的问题,其实要把握dp的主体是RGB color
public class Solution {
public int minCost(int[][] costs) {
if(costs == null || costs.length == 0) return 0;
int len = costs.length, red = 0, blue=0, green = 0;
for(int i=0; i<costs.length; i++){
int prevRed = red, prevGreen = green, prevBlue = blue;
red = costs[i][0] + Math.min(prevBlue, prevGreen);
blue = costs[i][1] + Math.min(prevRed, prevGreen);
green = costs[i][2] + Math.min(prevRed, prevBlue);
}
return Math.min(red, Math.min(blue, green));
}
}
二刷
长度为3的DP
public class Solution {
public int minCost(int[][] costs) {
if(costs == null || costs.length == 0) return 0;
int[] min = new int[3];
min[0] = costs[0][0];
min[1] = costs[0][1];
min[2] = costs[0][2];
int ori_0, ori_1, ori_2;
for(int i=1; i<costs.length; i++){
ori_0 = min[0]; ori_1 = min[1]; ori_2 = min[2];
min[0] = Math.min(ori_1, ori_2) + costs[i][0];
min[1] = Math.min(ori_0, ori_2) + costs[i][1];
min[2] = Math.min(ori_0, ori_1) + costs[i][2];
}
return Math.min(Math.min(min[0], min[1]), min[2]);
}
}