Description:
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.
小偷偷东西,在不能偷相邻两户人家的前提下尽可能地多偷东西。设在第i户人家时拥有的钱为mon[i],第i户人家的钱为nums[i],在第i户人家处,因为不能连续偷两户,因此如果偷的话获得的钱为在第i-2户人家时拥有的钱+第i户的钱(第i-1户不能偷),如果不偷的话就为在第i-1户人家时拥有的钱。i=0的时候显然必须偷(不偷的话会比偷少),i=1时则要与mon[0]比较,如果nums[1]>nums[0]的话则要偷,否则不偷(只有两家的话明显要偷有钱的)。i>=2时便可以用这条规则计算,即mon[i]=max(mon[i-2]+nums[i], mon[i-1])。
代码如下:
class Solution {
public:
int rob(vector<int>& nums) {
if(nums.size()==0)return 0;
else if(nums.size()==1)return nums[0];
else if(nums.size()==2)return max(nums[0],nums[1]);
else
{
int mon[nums.size()];
mon[0]=nums[0];
mon[1]=max(nums[0],nums[1]);
for(int i=2;i<nums.size();i++)
{
mon[i]=max(mon[i-2]+nums[i],mon[i-1]);
}
return mon[nums.size()-1];
}
}
};