House Robber
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了House Robber相关的知识,希望对你有一定的参考价值。
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.
假设房子的编号为0,n-1,nums[0...n-1] 存放钱数
解法一:
递归思想:
抢劫从编号为start房子开始,到end结束,所获得的利益为:
a)在抢劫第start房子时,int robed=nums[start]+rob(start+2,end),
b) 不抢劫start 房子时,int nonrobed=nums[start+1],
c)返回max(robed,nonrobed),该值作为 抢劫起始编号为start,结束为end的获得利益。
边界问题:当end>n-1 时,返回0,
观察该方法,在计算 抢劫起始编号为rob(start)时需要计算rob(start+2),计算rob(start+1)时也要计算rob(start+2),这时可以通过一个表来记录已经算过的值,
table[0,n-1] 第i项记录抢劫从i...n-1 房子获得的最大利益
代码:
class Solution {
public:
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==0)
return nums[0];
vector<int> table(size,-1);
return robCore(table,nums,0,size-1);
}
};
解法二:
解法一是正向思考,从编号start开始抢劫,直到end时获得的利益,现在从另一个方向思考,从编号0开始抢劫,到达编号i时获得的最大利益为maxV[i],
则maxV[i]=max(maxV[i-2]+nums[i],maxV[i-1])
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]);
vector<int> table(size,0);
table[0]=nums[0];
table[1]=max(nums[0],nums[1]);
for(int i=2;i<size;++i){
table[i]=max(table[i-1],table[i-2]+nums[i]);
}
return table[size-1];
}
优化空间
int size=nums.size();
if(size==0)
return 0;
if(size==1)
return nums[0];
if(size==2)
return max(nums[0],nums[1]);
int a=nums[0];
int b=max(nums[0],nums[1]);
for(int i=2;i<size;++i){
int temp=b;
b=max(b,a+nums[i]);
a=temp;
}
return b;
以上是关于House Robber的主要内容,如果未能解决你的问题,请参考以下文章