LeetCode 256. Paint House

There are a row of n houses, each house can be painted with one of the three colors: red, blue or green. 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 3 cost matrix. For example, costs[0][0] is the cost of painting house 0 with color red; costs[1][2] is the cost of painting house 1 with color green, and so on… Find the minimum cost to paint all houses.

Note:
All costs are positive integers.

思路:
1. 这代表一类题,遍历所有可能性,且遵循一定的约束条件。最直接的方法是,遍历所有可能性,找出最小cost,但这样的复杂度就是指数增长,o(2^n)。
2. 如何简化复杂度,减少不必要的运算?可以把问题看成是有层次的问题,这样就可以分割成小的问题,小的问题继续分成更小的问题,直到问题不能分割为止。和直接遍历把所有可能性平等的对待相比,这样有层次的方式,是把小问题解决了,大问题的解决就容易了,减少了遍历的可能性!因此,怎么看待或怎么建模这个问题,决定了采用什么方法解决这个问题。
3. 用DP,二维dp。找递推关系,小问题和大问题之间的逻辑联系!
2. 突然有个想法,应该设法总结一下,很多问题用简单粗暴的方法做,复杂度为什么很差?因此,需要借助一些辅助手段来回避这一类问题!

int minCost(vector<vector<int>>& costs) {
    int n=costs.size();
    vector<vector<int>> dp(n+1,vector<int>(3,0));//写完这一行,意识到是否可以不用新建array,直接在给定的2D array上做这个dp呢?
    for(int i=1;i<n;i++){
        vector<int> cur=costs[i-1];
        for(int j=0;i<3;j++){
            dp[i][j]=dp[i][j]+min(cur[(j+1)%3],cur[(j+2)%3]);
        }
    }
    return min(min(costs.back()[0],costs.back()[1]),costs.back()[2]);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值