240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 12 | Leetcode 265. Paint House II

题解

动态规划,Hard级别。

  1. Paint House 的升级版,如果颜色数量不是三种,而是若干种。直接套用256的思路,问题得解。
class Solution {
public:
    int minCostII(vector<vector<int>>& costs) {
        if(costs.empty()) return 0;
        
        int n = costs.size(), m = costs[0].size();

        // dp[i][j]: The min cost with the current house painted color j 
        vector<vector<int>> dp = costs;
        
        // dp[i][j] = costs[i][j] + min(dp[i-1][not j])
        for(int i = 1; i < n; i++) {
            for(int j = 0; j < m; j++) {
                int min_other = INT_MAX;
                for(int k = 0; k < m; k++) {
                    if(k != j && dp[i-1][k] < min_other) {
                        min_other = dp[i-1][k];
                    }
                }
                dp[i][j] += min_other;
            }
        }
        
        return *min_element(dp[n-1].begin(), dp[n-1].end());
    }
};

显然,还有优化空间,时间复杂度还可以下降。

posted @ 2020-09-24 03:08  CasperWin  阅读(75)  评论(0编辑  收藏  举报