您的位置:首页 > 其它

House Robber II

2016-06-17 14:33 316 查看
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place are arranged in a circle. That means the first house is the neighbor of the last
one. Meanwhile, the security system for these houses remain the same as for those in the previous street.

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.

思路:题目的意思是有一个强盗沿街去进行抢劫,但是这个街道是一个圆,每一家的房子中有一定数额的money,不能连续抢劫两家紧挨着的,求这个强盗最大的可以抢劫到的现金数。考虑这样一个问题,最后一家实际上和第一家是相邻的,如果一开始抢了第一家,这最后一家不能进行抢。不考虑最后一个元素,处理方式与House Robber I的方式是一样的,求出在dp[size-2]位置的最大值。加上最后一个元素后,由于最后一个与第一个相邻,不考虑第一个元素的时候求出在dp[size-1]处的最大值。两者之间最大的就是题目所要求的。想法比较直接,还有别的方法再补,此代码可以AC

代码如下:

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]);
if(size==3)
return max(max(nums[0],nums[1]),nums[2]);

vector<int>dp(size,0);
vector<int>dp2(size,0);
dp[0]=nums[0];
dp[1]=max(nums[0],nums[1]);
dp2[1]=nums[1];
dp2[2]=max(nums[1],nums[2]);
for(int i=3;i<size;i++)
{
dp2[i]=max(dp2[i-1],dp2[i-2]+nums[i]);
dp[i-1]=max(dp[i-2],dp[i-3]+nums[i-1]);
}
return max(dp2[size-1],dp[size-2]);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: