问题描述:
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.
解题思路:水题,设a[i]为前i间房子能抢劫到的最多钱数,状态转移方程 a[i]=max { a[i-1],a[i-2]+nums[i] }
代码:
#include<iostream>
#include<vector>
#include<cstring>
using namespace std;
class Solution {
public:
int rob(vector<int>& nums) {
int a[4000];
int len=nums.size();
if(len==0) return 0;
memset(a,0,sizeof(a));
a[0]=nums[0];
if(len==1) return a[0];
a[1]=nums[0]>nums[1]?nums[0]:nums[1];
for(int i=2;i<nums.size();i++){
a[i]=a[i-1]>(a[i-2]+nums[i])?a[i-1]:(a[i-2]+nums[i]);
}
return a[len-1]>a[len-2]?a[len-1]:a[len-2];
}
};
int main()
{
vector<int>nums;
nums.insert(nums.end(),1);
nums.insert(nums.end(),3);
nums.insert(nums.end(),1);
nums.insert(nums.end(),3);
nums.insert(nums.end(),100);
cout<<(new Solution())->rob(nums);
}