首页 > 其他 > 详细

[LeetCode] Paint House

时间:2015-08-14 15:18:25      阅读:2115      评论:0      收藏:0      [点我收藏+]

An interesting DP problem. This link 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<vector<int>>& 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).

[LeetCode] Paint House

原文:http://www.cnblogs.com/jcliBlogger/p/4729957.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!