【题目描述】
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.
【思路】动态规划题目,掌握的不够好。
maxval[i]=max(maxval[i-2]+nums[i],maxval[i-1])
【代码】
class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
vector<int> maxval(n,0);
if(n==0) return 0;
if(n==1) return nums[0];
maxval[0]=nums[0];
maxval[1]=max(nums[0],nums[1]);
for(int i=2;i<n;i++){
maxval[i]=max(maxval[i-2]+nums[i],maxval[i-1]);
}
return maxval[n-1];
}
};
解决一个专业窃贼如何在不触动相邻房屋警报系统的情况下,从一排房屋中盗窃最多金额的问题。采用动态规划方法,通过递推公式计算最大盗窃金额。
823

被折叠的 条评论
为什么被折叠?



