您的位置:首页 > 其它

Leetcode 198. House Robber

2017-02-08 13:58 316 查看
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.

s思路:

1. 用dp.从“不能抢相邻两家的钱”这个条件入手,例如:

num57102913
cur5715152428
pre057151524
如上图,cur表示当前位置时抢或不抢的最大值,pre表示前一个位置抢或不抢中最大。那么第二天当前位置有7,这就要比较了:如果抢,则总共就是7+上一个位置的pre,即:7+0=7;不抢,则就是上一个位置的cur=5,max(7,5)=7,递推关系:pre=cur, cur=max(cur,pre+nums[i])。

2. 为什么这类题可以用dp?首先,求最值问题,很多都可以考虑用dp,这个还不关键。最关键的是,抢到最多钱是个过程,且在过程中要一直保存抢到做多,就应为这个,我们可以把全程抢最多分割成n个小任务。又根据条件“不能抢相邻两家的钱”,这些任务之间还有联系,根据这个关系来得到递推关系即可!

3. “不能抢相邻两家的钱”,根据这个条件,说明只需要维护两个状态,当前位置和前一个位置的最大,然后不断更新当前和前一个位置。

//方法1:dp
class Solution {
public:
int rob(vector<int>& nums) {
//
if(nums.empty()) return 0;
int pre=0,cur=nums[0];
for(int i=1;i<nums.size();i++){
int tmp=max(cur,pre+nums[i]);
pre=cur;
cur=tmp;
}
return cur;
}
};


97b4
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dp