您的位置:首页 > 其它

198. House Robber

2016-03-28 23:42 267 查看
1.Question

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 it
will 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.
2.Code

class Solution {
public:
int rob(vector<int>& nums) {
if(nums.empty()) return 0;
if(nums.size() == 1) return nums[0];
vector<int> count(nums.size());
count[0] = nums[0];
count[1] = max(nums[0], nums[1]);
for(int i = 2; i < nums.size(); i++)
count[i] = max(nums[i] + count[i-2], count[i-1]);
return count.back();
}
};


3.Note

a.
这类问题应该想到DP。DP的关键是,找到状态 和 状态转移方程,一般会有一个或多个初始状态,而状态转移方程一般都能由递归方程写出。这个题的本质是,从一个数组中选择一些元素,使其和最大,而这个元素选择的约束条件是两两不能相邻。我们根据题意,可以想到DP的状态转移方程dp[i] = max(nums[i]+dp[i-2], dp[i-1])。

b.关于vector,还要熟悉一些常用的成员函数。

v.empty()判断v是否为空
v.size()返回v的size
v.begin()返回vector容器中起始元素的迭代器
v.end()返回vector容器中末尾元素的后一个地址
v.front()返回vector容器中起始元素的值
v.back()返回vector容器中末尾元素的值
v.push_back(elem)插入一个elem到容器的末尾
v.pop_back()弹出容器末尾的值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: