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.
思路:DP,第n个house如果paint color i, 那第n-1个house就不能。
注意minval1和minval2是前一次dp的最小值,而不是前一个costs的最小值。
class Solution {
public:
int minCostII(vector<vector<int>>& costs) {
if (costs.size() == || costs[].size() == ) return ;
int N = costs.size();
int K = costs[].size();
vector<vector<int>> dp(N, vector<int>(K, ));
for (int i = ; i < K; i++) dp[][i] = costs[][i];
for (int i = ; i < N; i++) {
int minval1 = INT_MAX, minval2 = INT_MAX;
int minidx1 = , minidx2 = ;
for (int j = ; j < K; j++) {
if (minval1 > dp[i-][j]) {
minval1 = dp[i-][j];
minidx1 = j;
}
}
for (int j = ; j < K; j++) {
if (minval2 > dp[i-][j] && j != minidx1) {
minval2 = dp[i-][j];
minidx2 = j;
}
}
for (int j = ; j < K; j++) {
if (minidx1 == j) dp[i][j] = costs[i][j] + minval2;
else dp[i][j] = costs[i][j] + minval1;
}
}
int minval = INT_MAX;
for (int i = ; i<K; i++) {
minval = min(minval, dp[N-][i]);
}
return minval;
}
};