[leetcode] 265. Paint House II 解题报告

46 篇文章 1 订阅
12 篇文章 0 订阅

题目链接:https://leetcode.com/problems/paint-house-ii/

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


思路:动态规划的题目,很容易想到思路,但是边界没有想清楚.

其状态转移方程应为: dp[i][j] = min(dp[i-1].begin(), dp[i-1].end()) + costs[i][j], 并且列不为j.

即对与每一个房子我们有k种方式来染色,而每种染色的代价是由上一栋房子不是染这种色的其余方案中最小值加上这个房子染当前颜色的代价来决定.

因此,最朴素的方式时间复杂度为O(n*k*k),即三层循环,分别是①遍历所有的房子.②遍历这个房子的所有颜色方案.③对于每种方案寻找上一个房子除了染这个颜色的最小代价.而空间复杂度则为O(n*k).

首先空间复杂度比较好优化到O(k),我们没有必要保存每一个房子的状态,因为每一栋房子的状态只会用到一次.

而时间复杂度也可以优化到O(n*k).在上述的循环②中,我们每遍历一种颜色都去寻找上一个房子除这个颜色之外的最小代价,这样会有很多重复的计算.而我们可以将循环③拿到和循环②同一层来预先做好,在②中要找最小代价的时候可以在O(1)的时间得到结果.这样就将时间优化到了O(n*k).

而如何预先处理能够使得循环②可以在O(1)时间得到上一栋房子除染这种颜色之外其他方案的代价呢?

我们可以利用两个数组一个保存从上一栋房子左到右当前的最小值.另一个从右到左保存上一栋房子染色方案从右向左的当前最小值.

而事实上还可以继续优化空间复杂度.我不想再去优化了,我觉得这样的时间空间复杂度已经足够了.而且代码会比较整洁.

代码如下:

class Solution {
public:
    int minCostII(vector<vector<int>>& costs) {
        if(costs.size() == 0) return 0;
        int m = costs.size(), n = costs[0].size();
        vector<int> dp(costs[0]);
        for(int i = 1; i < m; i++)
        {
            vector<int> left(n, INT_MAX), right(n, INT_MAX);
            for(int j =1; j< n; j++)   
                left[j] = min(left[j-1], dp[j-1]);
            for(int j =n-2; j>=0; j--) 
                right[j] = min(right[j+1], dp[j+1]); 
            for(int j =0; j< n; j++)
                dp[j] = min(left[j], right[j]) + costs[i][j];
        }
        return *min_element(dp.begin(), dp.end());
    }
};










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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值