动态规划——198. House Robber[easy]

本文介绍了一种解决“打家劫舍”问题的方法,该问题要求计算在一排房子里,不抢劫相邻房屋的情况下,所能获得的最大金额。通过动态规划的方式,递推计算每个房屋在被抢或不被抢时的最大收益。

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

计算小偷一晚上偷钱的最大数额,不能连续偷相邻两家,用数组nums代表每一家的现金数。


解题思路

令re[i]表示偷到 i 时的最大数额,re[n]即为所求。小偷在 i 时有两个选择:

1、偷,说明前一家没偷,此时最大数额为re[i-2]+ nums[i]

2、不偷,说明偷了前一家,此时数额为 re[i-1]


因此 re[i] = max(re[i-1],re[i-2]+ nums[i])


代码如下


class Solution {
public:
    int rob(vector<int>& nums) {
        if (nums.size() >= 3) {
		vector<int> re(nums.size(), 0);
		re[0] = nums[0];
		re[1] = re[1] = fmax(re[0], 0 + nums[1]);

		for (int i = 2; i < nums.size(); i++) {
			re[i] = fmax(re[i - 2] + nums[i], re[i - 1]);
		}

		return re[nums.size() - 1];
	}
	else if (nums.size() == 2) {
		return (nums[0] > nums[1]) ? nums[0] : nums[1];
	}
	else if (nums.size() == 1)
		return nums[0];
	else
		return 0;
    }
};

注意考虑nums大小,以及re[0]、re[1]的初始化:

可以考虑re[-2]、re[-1]都为0,从而得出re[0],re[1]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值