您的位置:首页 > 其它

#leetcode#198. House Robber

2016-04-27 16:58 267 查看
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.

动态规划?贪心?

第i个房子,i+1个房子,i+2个房子,第i+2个房子的收益为i个房子+第i+2个房子与i+1个房子中的较大者

class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
if(n<=0) return 0;
int ans
;
ans[0]=nums[0];
if(n==1) return ans[0];
ans[1]=(nums[0]>nums[1])?nums[0]:nums[1];
if(n==2) return ans[1];
int i;
for(i=2;i<n;i++)
{
int robn=ans[i-2]+nums[i];
ans[i]=(robn>ans[i-1])?robn:ans[i-1];
}
return ans[n-1];
}
};


精简代码,没必要去维护一个数组,只需要维护两个变量即可class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
if(n<=0) return 0;
int best=0;
int bestnow=0;
bestnow=nums[0];
if(n==1) return bestnow;
int i;
for(i=1;i<n;i++)
{
int temp=bestnow;
bestnow=((best+nums[i])>bestnow)?(best+nums[i]):bestnow;
best=temp;
}
return bestnow;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: