[leetcode] 198. 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 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.

这道题是窃贼偷东西,不能偷相邻的两个房子,题目难度为easy。

针对第N个房子,偷这个房子的话第N-1个房子不能偷,这样偷得赃款就是第N-2个房子累计的赃款加上第N个房子的钱;不偷这个房子的话赃款数就是第N-1个房子累计的赃款,取这两个中大的那个作为到第N个房子为止可以偷得的最大赃款数。这样可以采用动态规划的方法递推出最终可以获取的最大赃款数。具体代码:

class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.empty()) return 0;
        vector<int> money(nums.size(), 0);
        money[0] = nums[0];
        for(int i=1; i<nums.size(); i++) {
            money[i] = max(money[i-1], ((i>1)?money[i-2]:0)+nums[i]);
        }
        return money.back();
    }
};
另外,我们发现,到第N个房子累计的赃款数仅和第N-1和第N-2个房子的累计值有关,这样我们可以避免存储所有房子的赃款累计值,将空间复杂度降到O(1),具体代码:
class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.empty()) return 0;
        int money1 = 0, money2 = 0, money3 = 0;
        for(int i=0; i<nums.size(); i++) {
            money3 = max(money2, money1+nums[i]);
            money1 = money2;
            money2 = money3;
        }
        return money3;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值