Paint House II
Example
Challenge
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) {
// write your code here
if(costs == null || costs.length == 0 || costs[0].length == 0)
return 0;
int[][] dp = new int[costs.length][costs[0].length];
int min1 = -1, min2 = -1;
for (int i = 0; i < costs.length; i++ ){
int last1 = min1, last2 = min2;
min1 = -1;
min2 = -1;
for(int j = 0; j < costs[0].length; j++){
if(j != last1){
dp[i][j] = costs[i][j] + (last1 < 0 ? 0 : dp[i-1][last1]);
}
else{
dp[i][j] = costs[i][j] + (last2 < 0 ? 0 : dp[i-1][last2]);
}
if(min1 < 0 || dp[i][j] < dp[i][min1]){
min2 = min1;
min1 = j;
}
else if(min2 < 0 || dp[i][j] < dp[i][min2]){
min2 = j;
}
}
}
return dp[costs.length-1][min1];
}
}Last updated