198. House Robber

Description:

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.


简要题解:

采用动态规划的方法。

子问题c(i): 对于前i个房子,所能抢劫的最大金额。

第一个子问题c(0): 第0个房子的金钱数。

在解决各个子问题的过程中,需要维护两个与房子数量相同的数组: selected和notSelected。对于c(i),selected[i]表示在抢劫了第i个房子的情况下,所能抢劫的最大金额; notSelected[i]表示在补抢劫第i个房子的情况下,所能抢劫的最大金额。显然,c(i) = max(selected[i], notSelected[i])。

现在,来看看如何得到selected和notSelected的值。首先,我们有selected[0] = 第0个房子的金钱数,而notSelected[0] = 0。对于i > 0的情况,selected[i] = 第i个房子的金钱数 + notSeleted[i-1],而notSelected[i] = max(selected[i-1], notSelected[i-1])。至此,c(i)与c(i-1)间的关系也就建立起来了。接下来就是以c(0)为起点,不断地解决下一个问题。当c(i)包含了所有目标房子时,c(i)就是所要求的解。


代码:

#include<cmath>

using namespace std;

class Solution {
public:
    int rob(vector<int>& nums) {
        int sz = nums.size();

        if (0 == sz)
            return 0;

        vector<int> selected(sz, 0);
        vector<int> notSelected(sz, 0);

        selected[0] = nums[0];

          for (int i = 1; i < sz; i++) {
              selected[i] = nums[i] + notSelected[i-1];
              notSelected[i] = max(selected[i-1], notSelected[i-1]);
          }
        
        return max(selected.back(), notSelected.back());
    }
};


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值