标签:attention determine arranged security previous
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
解法:
该题目和第一个版本的不同点是,这里的房子时围成圆,相邻的两个房子不能同时被抢,
参考第一版本的方法,需要注意:
a)当第一个房子被抢时,最后一个房子不能被抢 即抢劫范围[0,n-2]
b)当第一个房子没被抢时,最后一个房子可以被抢,[1,n-1]
则需要对这两种情况,分别执行rob程序,取两种情况的最大值为最终结果
int robCore(vector<int> &table,vector<int> &nums,int start,int end){
if(start>end)
return 0;
if(table[start]!=-1)
return table[start];
int robed=nums[start]+robCore(table,nums,start+2,end);
int nonRobed=robCore(table,nums,start+1,end);
table[start]=max(robed,nonRobed);
return table[start];
}
int rob(vector<int>& nums) {
int size=nums.size();
if(size==0)
return 0;
if(size==1)
return nums[0];
vector<int> table(size,-1);
int robed= nums[0]+robCore(table,nums,2,size-2);
vector<int> table2(size,-1);
int nonrobed=robCore(table2,nums,1,size-1);
return max(robed,nonrobed);
}
解法二
同第一版本,同样可以用迭代方式求动态规划,
int robCore(vector<int> &nums,int start,int end){
int size=end-start+1;
if(start>end)//必须判断
return 0;
if(size==1)
return nums[start];
int a=nums[start];
int b=max(nums[start],nums[start+1]);
for(int i=start+2;i<=end;++i){
int temp=b;
b=max(a+nums[i],b);
a=temp;
}
return b;
}
int rob(vector<int>& nums) {
int size=nums.size();
if(size==0)
return 0;
if(size==1)
return nums[0];
int robed= nums[0]+robCore(nums,2,size-2);//注意,这里默认保证 end>=start
int nonrobed=robCore(nums,1,size-1);
return max(robed,nonrobed);
}
标签:attention determine arranged security previous
原文地址:http://searchcoding.blog.51cto.com/1335412/1750897