题目:
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.
典型的动态规划问题。假设OPT(i)为输入数据规模为i时的最优界,有如下方程。
OPT(1)=nums[1]
OPT(2)=max(nums[1],nums[2]).
OPT(n)=max(nums[n-1],nums[n-2]+wn) for n>=2
代码
class Solution {
public:
int rob(vector<int>& nums) {
if(nums.empty())
return 0;
unsigned long length = nums.size();
vector<int> opt;
for(int i=0;i<length;i++)
{
if(i==0)
opt.push_back(nums[0]);
if(i==1)
opt.push_back(max(nums[0],nums[1]));
if(i>=2)
opt.push_back(max(opt[i-1],opt[i-2]+nums[i]));
}
return opt[length-1];
}
};