### LeetCode  • ㊗️
• 大家
• offer
• 多多！

## Problem

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 an n x k cost matrix costs.

• For example, costs is the cost of painting house 0 with color 0; costs is the cost of painting house 1 with color 2, and so on…

Return the minimum cost to paint all houses.

Example 1:

Input: costs = [[1,5,3],[2,9,4]]
Output: 5
Explanation:
Paint house 0 into color 0, paint house 1 into color 2. Minimum cost: 1 + 4 = 5;
Or paint house 0 into color 2, paint house 1 into color 0. Minimum cost: 3 + 2 = 5.


Example 2:

Input: costs = [[1,3],[2,4]]
Output: 5


## Code

class Solution {
public int minCostII(int[][] costs) {
if(costs == null || costs.length == 0) return 0;

int n = costs.length;
int k = costs.length;

int min1 = -1;
int min2 = -1;

for(int i = 0; i < costs.length; i++){
int last1 = min1;
int last2 = min2;

min1 = -1;
min2 = -1;

for(int j = 0; j < k; j++){
if(j != last1){
costs[i][j] += last1 == -1 ? 0 : costs[i - 1][last1];
} else {
costs[i][j] += last2 == -1 ? 0 : costs[i - 1][last2];
}

if(min1 == -1 || costs[i][j] < costs[i][min1]){
min2 = min1;
min1 = j;
} else if (min2 == -1 || costs[i][j] < costs[i][min2]){
min2 = j;
}
}
}
return costs[n - 1][min1];
}
}