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

Note:
All costs are positive integers.

Follow up:
Could you solve it in O(nk) runtime?

思路

和《[Leetcode] 256. Paint House 解题报告》的思路一致,只不过这里不是三种颜色,而是k种颜色。我所做到的最优解是时间复杂度为O(n*k),空间复杂度是O(k)。这里动态规划的状态转移方程为:dp[i][j] = min(dp[i - 1].begin(), dp[i - 1].end()) + costs[i][j],并且min中的数不包括dp[j]。

1)空间复杂度的优化:由于dp[i]只和dp中的上一个状态相关,所以可以将空间复杂度从O(n*k)优化到O(k),即我们只记录刷到当前房子时的最优值。

2)时间复杂度的优化:在刷到第i个房子的时候,我们首先花费O(k)的时间找出截止i-1,花费最小和次小的方案,假设是最后一个房子刷成第lowest_index种颜色以及第lower_index种颜色这两种方案。这样在刷第i个房子的时候,如果验证第lowest_index个颜色,那么只需要基于dp[lower_index]这种方案;而验证其它颜色的时候,只需要基于dp[lowest_index]这种方案。

我觉得这应该是可以达到的最优解了。

代码

class Solution {
public:
    int minCostII(vector<vector<int>>& costs) {
        if(costs.size() == 0 || costs[0].size() == 0) {
            return 0; 
        }
        int n = costs.size(), k = costs[0].size();  
        if (k == 1) {
            int ret = 0;
            for (int i = 0; i < n; ++i) {
                ret += costs[i][0];
            }
            return ret;
        }
        vector<int> dp(costs[0]);  
        for(int i = 1; i < n; ++i) {
            int lowest_index = 0, lower_index = 1;
            if (dp[lower_index] < dp[lowest_index]) {
                swap(lowest_index, lower_index);
            }
            for (int j = 2; j < k; ++j) {
                if (dp[j] < dp[lower_index]) {
                    lower_index = j; 
                }
                if (dp[lower_index] < dp[lowest_index]) {
                    swap(lowest_index, lower_index);
                }
            }
            int lowest_value = dp[lowest_index], lower_value = dp[lower_index];
            for(int j = 0; j < k; ++j) { 
                if (j != lowest_index) {
                    dp[j] = lowest_value + costs[i][j];
                } 
                else {
                    dp[j] = lower_value + costs[i][j];
                }
            }
        }  
        return *min_element(dp.begin(), dp.end());  
    }
};

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值