LeetCode -- 198. House Robber

解决一道经典动态规划题目,探讨如何在不连续抢劫相邻房屋的情况下获得最大收益。通过递推公式dist[i]=max(dist[i−1],dist[i−2]+nums[i])来计算最优解。

摘要生成于 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.


思路:
这道题是一个动态规划题,既然是动态规划,那么就得找到状态转移方程,这道题本质是求不相邻数组元素的最大组合问题,考虑抢劫到第i 家时,抢到的总钱数dist[i],第i家抢与不抢只与i-1是否被抢有关。所以:
dist[i]=max(dist[i1],dist[i2]+nums[i]),i>2
初始时:dist[0]=nums[0]dist[1]=max(nums[0],nums[1])
此时问题就被完美解决了。


C++实现:

class Solution {
public:
    int rob(vector<int>& nums) {
        if(nums.size()==0)
            return 0;
        if(nums.size()==1)
            return nums[0];

        vector<int> dist(nums.size(), 0);

        dist[0] = nums[0];
        dist[1] = max(nums[0], nums[1]);
        for(int i=2; i<nums.size(); ++i){
            dist[i] = max(dist[i-1], dist[i-2]+nums[i]);
        }
        return dist[nums.size()-1];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值