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

本文共 1551 字,大约阅读时间需要 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).

转载地址:http://gsgzl.baihongyu.com/

你可能感兴趣的文章
数据操作与查询语句
查看>>
selenium webdriver (11) -- 截图
查看>>
sublime插件安装
查看>>
网络配置多会话实验
查看>>
如何挑选适合自己的HTML5视频课程
查看>>
windows提权
查看>>
苹果Siri再新增服务内容 航班查询、餐点外送和血糖监控
查看>>
学习笔记
查看>>
远程协助,TeamViewer之外的另一种选择
查看>>
Centos 6.5 部署 LNMP
查看>>
网安天目
查看>>
rsync远程同步及rsync+inotify实时同步
查看>>
Redis分布式锁的正确实现方式(Java版)
查看>>
Linux20180427
查看>>
linux系统配置及服务管理第一章系统部署
查看>>
SQL语句优化:show参数
查看>>
webstorm那些常用快捷键
查看>>
MySQL5.7 group by新特性报错1055的解决办法
查看>>
网易企业邮箱的萨班斯归档是什么?
查看>>
阿里架构师告诉你最新Java架构师学习路线图
查看>>