[LeetCode][DP] 265. Paint House II

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 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?

Solution

class Solution {
public:
    int minCostII(vector<vector<int>>& costs) {
        if (costs.size() == 0) {
            return 0;
        }
        
        vector<vector<int>> f(2, vector<int>(costs[0].size())); // 滾動(dòng)數(shù)組
        
        for(int i = 0; i < costs[0].size(); i++) {
            f[0][i] = costs[0][i];
        }
        
        for(int i = 1; i < costs.size(); i++) {
            int index = i % 2;
            for(int j = 0; j < costs[i].size(); j++) {
                f[index][j] = INT_MAX;
                for(int k = 0; k < costs[i].size(); k++) {
                    if (j != k) { // 確保當(dāng)前選的顏色和前一個(gè)顏色不一樣
                        f[index][j] = min(f[index][j], f[1-index][k] + costs[i][j]);
                    }
                }
            }
        }
        
        int minCost = INT_MAX;
        int index = (costs.size() - 1) % 2;
        for(int i = 0; i < costs[costs.size() - 1].size(); i++) {
            minCost = min(minCost, f[index][i]);
        }
        
        return minCost;
    }
};
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容