这里有n
个房子在一列直线上,现在我们需要给房屋染色,分别有红色蓝色和绿色。每个房屋染不同的颜色费用也不同,你需要设计一种染色方案使得相邻的房屋颜色不同,并且费用最小。
费用通过一个n
x3
的矩阵给出,比如cost[0][0]
表示房屋0
染红色的费用,cost[1][2]
表示房屋1
染绿色的费用。
注意事项
所有费用都是正整数
样例
costs
= [[14,2,11],[11,14,5],[14,3,10]]
return 10
房屋 0
蓝色, 房屋 1
绿色, 房屋 2
蓝色, 2 + 5 + 3 = 10
public class Solution {
/**
* @param costs n x 3 cost matrix
* @return an integer, the minimum cost to paint all houses
*/
public int minCost(int[][] costs) {
int n = costs.length;
if(n==0) return 0;
//dp,0~i染色完后的最小染色支出
int[] dp = new int[3];
dp = costs[0];
for(int i=1; i<n; i++){
int[] tmp = new int[3];
tmp[0] = Math.min(dp[1], dp[2])+costs[i][0];
tmp[1] = Math.min(dp[0], dp[2])+costs[i][1];
tmp[2] = Math.min(dp[1], dp[0])+costs[i][2];
dp = tmp;
}
return Math.min(dp[0], Math.min(dp[1], dp[2]));
}
}