Leetcode House Robber系列
2015-08-07 20:24
351 查看
Leetcode #198 House Robber
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and itwill automatically contact the police if two adjacent houses were broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
class Solution { public: int rob(vector<int> &num) { int n = num.size(); if(n == 0) return 0; if(n == 1) return num[0]; vector<int> dp(n, 0); dp[0] = num[0]; dp[1] = max(num[0], num[1]); for(int i = 2; i < n; i ++) dp[i] = max(dp[i-2] + num[i], dp[i-1]); return dp[n-1]; } };
Leetcode #213 House Robber II
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the
first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
class Solution {
public:
int rob(vector<int> &num) {
int n = num.size();
if(n == 0) return 0;
if(n == 1) return num[0];
if(n == 2) return max(num[0], num[1]);
vector<int> dp(n, 0);
dp[1] = num[1]; dp[2] = max(num[1], num[2]);
for(int i = 3; i < n; i ++)
dp[i] = max(dp[i-2] + num[i], dp[i-1]);
int ans = dp[n-1];
dp[0] = num[0]; dp[1] = max(num[0], num[1]);
for(int i = 2; i < n - 1; i ++)
dp[i] = max(dp[i-2] + num[i], dp[i-1]);
ans = max(ans, dp[n-2]);
return ans;
}
};
相关文章推荐
- poj 1989 数学(求一个序列的最短非子序列长)
- 四年北航计算机怎么读呢?
- muduo::Buffer分析
- 点灯笼
- 1657: 求日龄
- 递归摘录
- IOS界面适配一: Pt与Px的关系
- 九个衡量 Rails 应用性能的小方法
- 基本命令(按学习进度随机添加)
- Caused by: java.lang.IllegalStateException: Per-clause not recognized
- Java编程思想重点笔记(Java开发必看)
- UVa 10806 Dijkstra, Dijkstra (无向图+最小费用最大流+最短路:)
- ORM进阶之 ORM简介
- 在google地图上显示路线
- python机器学习库 :matplotlib
- Glyph Metrics
- Web Service修炼之五WS-Security
- 全方位了解CSS3的Regions扩展
- IO学习
- HDOJ 5348 MZL's endless loop