题目:
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.
解答:
很明显的dp,用dp[i]表示最后偷得一家是i,那么公式为dp[i] = max{dp[j] + nums[i]}, 0 <=j <=i - 2;
class Solution {
public:
int rob(vector<int>& nums) {
int size = nums.size();
if(size == 0)
return 0;
if(size == 1)
return nums[0];
if(size == 2)
return max(nums[0],nums[1]);
vector<int> dp;
dp.push_back(nums[0]);
dp.push_back(nums[1]);
for(int i = 2;i < size;++i)
{
int max = 0;
for(int j = 0;j < i - 1;++j)
{
if(nums[i] + dp[j] > max)
max = nums[i] + dp[j];
}
dp.push_back(max);
}
int res = 0;
for(int j = 0;j <size;++j)
{
if(dp[j] > res)
res = dp[j];
}
return res;
}
};