Paint House

There are a row of n houses, each house can be painted with one of the k colors. 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 k cost matrix. For example, costs[0][0] is the cost of painting house 0 with color 0costs[1][2] is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.

Example

Given n = 3, k = 3, costs = [[14,2,11],[11,14,5],[14,3,10]] return10

house 0 is color 2, house 1 is color 3, house 2 is color 2, 2 + 5 + 3 = 10

分析:

这题和在一个矩阵上冲一个点走到另一个点所需的cost是一样的。

从第二个房子开始,找出使用和上一家不同颜色能够获取的最小的cost。最后一排就可以算出总的价格。

 public class Solution {
/**
* @param costs n x k cost matrix
* @return an integer, the minimum cost to paint all houses
*/
public int minCostII(int[][] costs) {
if (costs == null || costs.length == || costs[].length == ) return ; for (int i = ; i < costs.length; i++) {
for (int j = ; j < costs[].length; j++) {
int tempMin = Integer.MAX_VALUE;
for (int k = ; k < costs[].length; k++) {
if (k != j) {
if (tempMin > costs[i - ][k]) {
tempMin = costs[i - ][k];
}
}
}
costs[i][j] += tempMin;
}
}
int tempMin = Integer.MAX_VALUE;
for (int j = ; j < costs[].length; j++) {
if (costs[costs.length - ][j] < tempMin) {
tempMin = costs[costs.length - ][j];
}
}
return tempMin;
}
}
上一篇:git操作+一个本地项目推到github上+注意


下一篇:BZOJ4128Matrix——hash+矩阵乘法+BSGS