[LeetCode] 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.

动态规划。状态转移方程为:dp[i] = max(dp[i-1], dp[i-2] + num[i])

 1 class Solution {
 2 public:
 3     int rob(vector<int> &num) {
 4         int n = num.size();
 5         if (n == 0) return 0;
 6         vector<int> dp(n, 0);
 7         dp[0] = num[0];
 8         for (int i = 1; i < n; ++i) {
 9             if (i < 2) dp[i] = max(dp[i-1], num[i]);
10             else dp[i] = max(dp[i-1], dp[i-2] + num[i]);
11         }
12         return dp[n-1];
13     }
14 };

 还是动规,分别维护到奇数下标时和到偶数下标时的最大和。

 1 class Solution {
 2 public:
 3     int rob(vector<int> &num) {
 4         int odd = 0, even = 0;
 5         for (int i = 0; i < num.size(); ++i) {
 6             if (i & 0x1) odd = max(odd + num[i], even);
 7             else even = max(even + num[i], odd);
 8         }
 9         return max(odd, even);
10     }
11 };

 

转载于:https://www.cnblogs.com/easonliu/p/4384008.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值