原题链接在这里:https://leetcode.com/problems/paint-house-ii/
题目:
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 0; costs[1][2]
is the cost of painting house 1 with color 2, and so on... Find the minimum cost to paint all houses.
Note:
All costs are positive integers.
题解:
类似Paint House. k中不同的颜色. paint当前house时, 若是当前的颜色k与之前最小cost的颜色不同时,加上之前的最小值. 若是当前k与之前相同就选之前给出第二小cost的颜色.
Time Complexity: O(kn). Space: O(1).
AC Java:
public class Solution {
public int minCostII(int[][] costs) {
if(costs == null || costs.length == 0){
return 0;
}
int min1 = 0; //当前这个house涂完最小的cost
int min2 = 0; //当前这个house涂完第二小的cost
int lastColor = -1; //上个house选择的颜色
for(int i = 0; i<costs.length; i++){
int curMin1 = Integer.MAX_VALUE; //选择到当前颜色时的最小cost
int curMin2 = Integer.MAX_VALUE; //选择到当前颜色时的第二小cost
int curColor = -1;
for(int k = 0; k<costs[i].length; k++){
int newCost = costs[i][k] + (k == lastColor ? min2 : min1);
if(newCost < curMin1){
curMin2 = curMin1;
curMin1 = newCost;
curColor = k;
}else if(newCost < curMin2){
curMin2 = newCost;
}
}
min1 = curMin1;
min2 = curMin2;
lastColor = curColor;
}
return min1;
}
}