213. House Robber II
- Total Accepted: 41692
- Total Submissions: 127872
- Difficulty: Medium
- Contributors: Admin
Note: This is an extension of House Robber.
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.
解题思路:
本题在House Robber基础上将所有的房子由线性排列变成了环形排列。即增加了不能同时偷第一户和最后一户人家的限制。所以本题其实可以看作第一题的两种不同情况。第一种就是取第一户,不取最后一户。第二种为取最后一户,不取第一户。然后返回两种情况中较大的那个结果即可。
代码展示:
class Solution {
public:
vector<int> res1;
vector<int> res2;
int help(vector<int> nums,int n,int type)
{
//two different conditons
if(type)
{
if(res1[n]!=-1) return res1[n];
if(n==0)
{
res1[0]==nums[0];
return nums[0];
}
if(n==1)
{
res1[1]=max(nums[0],nums[1]);
return res1[1];
}
else
{
res1[n]=max(nums[n]+help(nums,n-2,1),help(nums,n-1,1));
return res1[n];
}
}
else
{
if(res2[n]!=-1) return res2[n];
if(n==0)
{
res2[0]==nums[0];
return nums[0];
}
if(n==1)
{
res2[1]=max(nums[0],nums[1]);
return res2[1];
}
else
{
res2[n]=max(nums[n]+help(nums,n-2,0),help(nums,n-1,0));
return res2[n];
}
}
}
int rob(vector<int>& nums) {
int n= nums.size();
if(!n) return 0;
if(n==1) return nums[0];
if(n==2) return max(nums[0],nums[1]);
if(n==3) return max(max(nums[0],nums[1]),nums[2]);
vector<int> n1;
vector<int> n2;
for(int i=0;i<n;i++)
{ res2.push_back(-1);
res1.push_back(-1);
//n1 , n2 represent different type
if(i<n-1) n1.push_back(nums[i]);
if(i>0) n2.push_back(nums[i]);
}
return max(help(n1,n-2,1),help(n2,n-2,0));
}
};