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 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.
本题是一道简单的动态规划题目,本质上是求一个数组中不连续数字的最大和,状态转移方程如下:
设置maxV[i]表示到第i个房子位置时的最大收益。
递推关系为maxV[i] = max(maxV[i-2]+num[i], maxV[i-1]) 第一项表示不抢第i-1个房子,那么可以抢第i个房子;第二项表示不抢第i个房子,那么此时收益等于在i-1个房子的收益
注:可能会对上述递推关系产生疑问,是否存在如下可能性,maxV[i-1]并不含num[i-1]?
结论是,在这种情况下maxV[i-1]等同于maxV[i-2],因此maxV[i-2]+num[i]更大,转移方程依然成立。
代码如下:
1 class Solution { 2 public: 3 int rob(vector<int>& nums) { 4 int n = nums.size(); 5 vector<int> dp(n,0); 6 if (n == 0) 7 return 0; 8 else if (n == 1 ) 9 return nums[0]; 10 else if (n == 2) 11 return max(nums[0],nums[1]); 12 else 13 { 14 dp[0] = nums[0]; 15 //dp[1] = nums[1];//; 16 dp[1] = max(nums[0],nums[1]); //这里要小心 17 for (int i = 2; i < n; i++) 18 { 19 dp[i] = max(dp[i-1],dp[i-2]+nums[i]); 20 } 21 } 22 return dp[n-1]; 23 24 } 25 };
推荐一篇非常精彩的讲解这道题的博客,注意看评论,http://www.cnblogs.com/grandyang/p/4383632.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步