博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Paint House
阅读量:5917 次
发布时间:2019-06-19

本文共 1606 字,大约阅读时间需要 5 分钟。

Problem Description:

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.


An interesting DP problem. posts a nice solution which gives costs[i][j] a new meaning and modify it directly and so save the usage of additional spaces.

Well, personally I would like to keep costs unmodified. I rewrite the code in C++, a little verbose than the one in the above link:-)

1 class Solution { 2 public: 3     int minCost(vector
>& costs) { 4 if (costs.empty()) return 0; 5 int n = costs.size(), r = 0, g = 0, b = 0; 6 for (int i = 0; i < n; i++) { 7 int rr = r, bb = b, gg = g; 8 r = costs[i][0] + min(bb, gg); 9 b = costs[i][1] + min(rr, gg);10 g = costs[i][2] + min(rr, bb);11 }12 return min(r, min(b, g));13 } 14 };

r/b/g in the i-th loop means the minimum costs to paint the i-th house in red/blue/green respectively plus painting the previous houses. The time and space complexities are still ofO(n) and O(1).

转载于:https://www.cnblogs.com/jcliBlogger/p/4729957.html

你可能感兴趣的文章
ASP.NET Web API中参数的传递方式
查看>>
grep用法详解:grep与正则表达式
查看>>
sed实现直接修改文件内容
查看>>
Android内核开发:系统分区与镜像文件的烧写
查看>>
U盘量产--多系统安装
查看>>
安装unixODBC安装连接mysql
查看>>
Android Bug 汇总
查看>>
分布列表实现的简单路由过滤
查看>>
iOS开发之MapKit
查看>>
SQLServer2012表表达式练习
查看>>
APScheduler(Advance Python Scheduler) ImportError:
查看>>
[deviceone开发]-动态添加组件add方法的示例
查看>>
Thread Safety,PHP判断nts与ts
查看>>
探讨面向对象的一些缺陷
查看>>
HUB
查看>>
各类人群营养保健
查看>>
[office]excel2011 vlookup
查看>>
备份架构——三种基本备份拓扑
查看>>
django数据模型中关于on_delete的使用
查看>>
下拉刷新SwipeRefreshLayout源码
查看>>