您的位置:首页 > 其它

leetcode解题报告:213. House Robber II

2016-10-31 16:01 393 查看
题意:

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.

难度:Medium

解题思路: 时间复杂度O(n)、空间复杂度O(n),这道题大意上是说房子排成圆形,一个小偷偷了某个房子的话不能偷和它相邻的房子,和排成一排的情况相比,不同之处在于第一栋和最后一栋房子不能同时偷。 那么可以把问题分成两种情况,(1)不偷最后一栋房子的情况,(2)不偷第一个房子的情况。 对于情况(1),dp数组从第一栋房子开始递推,dp[i]表示到第i个房子最多可以偷到多少钱,dp[0]=nums[0],dp[1]=max(dp[0],nums[1]),此后dp[i]=max(dp[i-1],dp[i-2]+nums[i])表示前一栋房子如果偷了,这个房子就不能再偷,如果前一栋房子没偷,就可以偷这个房子。
注意情况(1)dp数组只递推到最后一栋房子之前的那一栋,最后一栋房子的dp值是不计算的。 取这种情况下最大可以偷得max1.

 对于 情况(2),则是从第二栋房子开始递推,一直递推到最后一栋房子,第一栋房子不计算dp值,这种情况下最大可以偷得max2

最后只要比较max1和max2,返回比较大的那一个即可。

class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
if(nums.size()==0)
return 0;
if(nums.size()==1)
return nums[0];
if(nums.size()==2)
return max(nums[0],nums[1]);
vector<int> dp(nums.size()+1,-1);

dp[1]=nums[1];
dp[2]=max(dp[1],nums[2]);
for(int i = 3;i<n;i++)
{
dp[i]=max(dp[i-1],dp[i-2]+nums[i]);
}
int max1=dp[n-1];
dp[0]=nums[0];
dp[1]=max(nums[1],dp[0]);
for( int i=2;i<n-1;i++)
{
dp[i]=max(dp[i-1],dp[i-2]+nums[i]);

}
int max2=dp[n-2];
return max(max1,max2);

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: