# [LeetCode265]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 is the cost of painting house 0 with color 0; costs 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.

Could you solve it in O(nk) runtime?

Hide Company Tags Facebook
Hide Tags Dynamic Programming
Hide Similar Problems (M) Product of Array Except Self (H) Sliding Window Maximum (M) Paint House (E) Paint Fence
``````

dp[j]: 刷前i個房子且最後一個房子用的是j顏色的minimum cost。
min1: 刷前i個房子最後用某個顏色時最小的cost。
min2: 刷前i個房子最後用另外某個顏色時第二小的cost。

``````class Solution {
public:
int minCostII(vector<vector<int>>& costs) {
if (costs.empty()) return 0;
int n = costs.size(), k = costs.size(), min1 = 0, min2 = 0;
vector<int> dp(k,0);
for(int i = 0; i<n; ++i){
int tmp1 = min1, tmp2 = min2;
min1 = min2 = INT_MAX;
for(int j = 0; j<k; ++j){
dp[j] = ((dp[j] == tmp1) ? tmp2 : tmp1) + costs[i][j];
if(min1 <= dp[j]) min2 = min(min2, dp[j]);
else{
min2 = min1;
min1 = dp[j];
}
}
}
return min1;
}
};``````