[week 11][Leetcode][Dynamic Programming] House Robber

  • Question:

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 andit 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 tonightwithout alerting the police.


  • Analysis:
这是一道关于动态规划的题目,需要求出小偷一个晚上最多可以偷到的金钱数目。举个例子将会很容易看出其中的关系,比如一条街上每户人家的金额为[6,12,8,9,10,4,3]。首先从第一,二户人家中选择一户进行偷盗,所以金额不变,到第三户人家时,此时小偷可以偷到的最大金额为:6,12,14,9,10,4,3;到第四户人家时,小偷只需要考虑排在他之前的第二和第三户人家的金额,此时他偷盗第四户时可以偷盗的最大金额为:6,12,14,21,10,4,3;以此类推,到第五户人家时:6,12,14,21,24,4,3;第六户:6,12,14,21,24,25,3;最后一户:6,12,14,21,24,25,27。所以一个晚上他可以偷盗且不会引起报警的金额为27。由这个例子我们可以明显看出其状态转移方程为:F[n] = max{F[n-2],F[n-3]} + F[n]。代码如下所示。
  • Code:
class Solution {
public:
    int rob(vector<int>& nums) {
        const int n = nums.size();
        int result = 0;
        if (n==0)
            return 0;
        
        if (n == 1)
            return nums[0];
        
        if (n == 2)
        {
            result = max(nums[0],nums[1]);
            return result;
        }
        
        if (n == 3)
        {
            result = max(nums[1],(nums[0]+nums[2]));
            return result;
        }
        
        if (n >= 4)
        {
            nums[2] += nums[0];
            result = nums[2];
            for (int i=3;i<n;i++)
            {
                nums[i] = max(nums[i-2],nums[i-3])+nums[i];
                result = max(result,nums[i]);
            }
            return result;
        }
        
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值