here 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 anx3cost matrix. For example,costs[0][0]is the cost of painting house0with color red;costs[1][2]is the cost of painting house1with color green, and so on... Find the minimum cost to paint all houses.
Notice
All costs are positive integers.
Have you met this question in a real interview?
Yes
Example
Givencosts=[[14,2,11],[11,14,5],[14,3,10]]return10
house 0 is blue, house 1 is green, house 2 is blue,2 + 5 + 3 = 10
DP.
set f[n][0], f[n][1], f[n][2] represents the min sum for the first n houses and the n - 1th house is painted with red, blue, green
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) {
// Write your code here
if (costs == null || costs.length == 0 || costs[0] == null || costs[0].length == 0) {
return 0;
}
int n = costs.length;
int m = costs[0].length;
int[][] f = new int[2][m];
int now, old = 0;
int i, j, k;
for (i = 1; i <= n; i++) {
old = now;
now = 1 - now;
for (j = 0; j < m; j++) {
f[now][j] = Integer.MAX_VALUE;
for (k = 0; k < m; k++) {
if (j == k) {
continue;
}
f[now][j] = Math.min(f[now][j], f[old][k] + costs[i - 1][j]);
}
}
}
return Math.min(f[now][0], Math.min(f[now][1], f[now][2]));
}
}