[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[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.

Follow up:
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

這題這麼不簡單,我當然不會。參考了大家的O(nk)方法。
dp[j]: 刷前i個房子且最後一個房子用的是j顏色的minimum cost。
min1: 刷前i個房子最後用某個顏色時最小的cost。
min2: 刷前i個房子最後用另外某個顏色時第二小的cost。

對於當前房子,如果之前的房子的minimum cost並不是min1 我們可以直接選取min1的顏色,否則選取min2的顏色。因爲只要相鄰兩個房子顏色不一樣即可。

class Solution {
public:
    int minCostII(vector<vector<int>>& costs) {
        if (costs.empty()) return 0;
        int n = costs.size(), k = costs[0].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;
    }
};
發佈了109 篇原創文章 · 獲贊 0 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章