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.
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.
很明显,这是一道动态规划的题目,在tag中也标明了。
可以这样分析:
先说明两个数组的含义:
rob[N]:表示到第N家商户的最大化收益
notRob[N]:表示在不抢劫第N家商户的前提下的最大化收益。
继续…..
如果这条街道上只有一家商户,为了利益最大化,你决定抢,则为rob[0] = num.at(0),但是你忽然发善心,不抢了,则notRob[0] = 0.
之后这条街道繁荣起来了,商户变多,假设有N家商户,此时你已经“处理(抢或者不抢巴拉巴拉)”了前N-1家商户,来到了第N家商户的门前。那么摆在你面前的选择题如下:
1、对第N家商户不抢,则你的最大化收益就是截止到第N-1商户的收益,即notRob[N] = r[N - 1];
rob[N] = rob[N - 1];
2、假设你要对第N家商户动手,那么有一个重要的前提就是:你没有抢劫第N-1家商户。则收益为
rob[N] = notRob[N - 1] + num.at(N) > rob[N] ? notRob[N - 1] + num.at(N) : rob[N];
按照这个规则你一直抢到最后一家商户,比较一下notRob[N]和rob[N]哪个比较大就ok了。
(PS:可能还要压缩的空间。。但是这样比较直观。。)
class Solution {
public:
int rob(vector& nums) {
int *r;
int *nr;
//r[N]:表示到第N家商户的最大化收益
//nr[N]:表示在不抢劫第N家商户的前提下的最大化收益。
if(0 == nums.size())
{
return 0;
}
r = new int[nums.size()];
nr = new int[nums.size()];
//第一家肯定要偷
r[0]=nums.at(0);
nr[0]=0;
for (int day=1;dayr[day])
{
r[day]=r[day-1];
}
}
int re=nr[nums.size()- 1];
if (re