LC 265. 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.
思路:DP,第n个house如果paint color i, 那第n-1个house就不能。
注意minval1和minval2是前一次dp的最小值,而不是前一个costs的最小值。
1 class Solution { 2 public: 3 int minCostII(vector<vector<int>>& costs) { 4 if (costs.size() == 0 || costs[0].size() == 0) return 0; 5 int N = costs.size(); 6 int K = costs[0].size(); 7 vector<vector<int>> dp(N, vector<int>(K, 0)); 8 for (int i = 0; i < K; i++) dp[0][i] = costs[0][i]; 9 for (int i = 1; i < N; i++) { 10 int minval1 = INT_MAX, minval2 = INT_MAX; 11 int minidx1 = 0, minidx2 = 0; 12 for (int j = 0; j < K; j++) { 13 if (minval1 > dp[i-1][j]) { 14 minval1 = dp[i-1][j]; 15 minidx1 = j; 16 } 17 } 18 for (int j = 0; j < K; j++) { 19 if (minval2 > dp[i-1][j] && j != minidx1) { 20 minval2 = dp[i-1][j]; 21 minidx2 = j; 22 } 23 } 24 for (int j = 0; j < K; j++) { 25 if (minidx1 == j) dp[i][j] = costs[i][j] + minval2; 26 else dp[i][j] = costs[i][j] + minval1; 27 } 28 } 29 int minval = INT_MAX; 30 for (int i = 0; i<K; i++) { 31 minval = min(minval, dp[N-1][i]); 32 } 33 return minval; 34 } 35 };