算法分析与设计——LeetCode:198. House Robber

本文探讨了一种抢劫房屋的问题,其中相邻房屋安装了联动报警系统。通过动态规划的方法,文章提供了一个高效的解决方案来确定在不触发报警的情况下,能够获得的最大金额。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

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.

Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.

class Solution {
public:
    int rob(vector<int>& nums) {
    }
};

思路

这道题的意思是在一个数组nums中,对于每个i,nums[i]和nums[i+1]最多只能选择一个,求能选出的最大和。这就涉及到了动态规划。如下代码,a[i]代表当前数nums[i]没有选中时前i+1个数的最大和,b[i]代表当前数nums[i]选中时前i+1个数的最大和。
对于每个i>0,均有:
    a[i]:当前数没有选中,则前一个数nums[i-1]可选可不选,a[i] = max(a[i-1], b[i-1])
    b[i]:当前数选中,则前一个数nums[i-1]不可选,b[i] = a[i-1]+nums[i]
最后再比较当a[n-1],b[n-1]的大小,取最大值,即含有n个数的数组的前n个数的最大和。
上面描述的是下面我注释掉的代码,新增加的代码是在注释的代码基础上进行的小修改,可以少用两个数组,节省空间。
时间复杂度为O(n)。

代码

class Solution {
public:
    int rob(vector<int>& nums) {
        int size = nums.size();
        if (size == 0) {
            return 0;
        }
        /*int* a = new int[size];
        int* b = new int[size];
        a[0] = 0;
        b[0] = nums[0];
        for (int i = 1; i < size; i++) {
            b[i] = a[i-1]+nums[i];
            a[i] = max(a[i-1], b[i-1]);
        }
        return max(a[size-1], b[size-1]);*/
        int a = 0, b = nums[0];
        for (int i = 1; i < size; i++) {
            int tb = b, ta = a;
            b = ta+nums[i];
            a = max(ta, tb);
        }
        return max(a, b);
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值