198. House Robber

21 篇文章 0 订阅
12 篇文章 0 订阅

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.

思路参考:http://blog.csdn.net/chilseasai/article/details/50631233

解答:
动态规划一定要找递推公式。
对每一家房子,在其前一家房子偷不偷的前提下,有两种可能的情况。 前一家房子被偷了,它就不能再偷了。前一家房子没被偷,它可以被偷也可以选择不偷。
根据上述分析,得到递推公式:
money[i][0] = max(money[i - 1][0], money[i - 1][1])
上述公式表示,不偷第 i 家房子,当前最大收益就是前一家房子的最大收益,前一家房子可能被偷了,也可能没有被偷。
money[i][1] = money[i - 1][0] + nums[i]
上述公式表示,要偷第 i 家的房子,必须在不偷第 i-1 家房子的前提下,才能加上偷第 i 家获得的收益。

class Solution {  
public:  
    int rob(vector<int> &num) {  
        if(num.size() == 0) return 0;
        int money0 = 0;   // 表示没有选择当前house
        int money1 = num[0];   // 表示选择了当前house  
        for(int i = 1; i < num.size(); i++){
            int temp = money0;  
            money0 = max(money0, money1); // 没有选择当前house,那么它等于上次选择了或没选择的最大值  
            money1 = temp + num[i]; // 选择了当前houses,值只能等于上次没选择的+当前house的money  
        }  
        return max(money0, money1); 
    }  
};  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值