[Leetcode] 198. House Robber 解题报告
来源:互联网 发布:w7内外网转换软件 编辑:程序博客网 时间:2024/05/20 06:52
题目:
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.
思路:
这是一道简单的动态规划题目。设dp[i]表示截止第i个位置可以获得的最大抢劫钱数,则有如下两种情况:
1)如果要抢当前家庭,则上家不能抢,因此受益为dp[i + i] = dp[i - 1] + nums[i + 1];
2)如果不抢当前家庭,则受益同其前驱,即dp[i + 1] = dp[i]。注意dp[i]并不一定意味着一定抢劫了第i家。
因此状态转移方程为:dp[i + 1] = max(dp[i - 1] + nums[i + 1], dp[i])。算法的时间复杂度是O(n),空间复杂度是O(n)。但是从状态转移方程来看,dp[i+1]只和dp[i-1]以及dp[1]相关,因此可以进一步优化,将空间复杂度降低到O(1)。下面是优化后的代码片段。
代码:
class Solution {public: int rob(vector<int>& nums) { if (nums.size() == 0) { return 0; } if (nums.size() == 1) { return nums[0]; } int value0 = nums[0], value1 = max(value0, nums[1]); for (size_t i = 2; i < nums.size(); ++i) { int max_value = max(value0 + nums[i], value1); value0 = value1; value1 = max_value; } return value1; }};
- [leetcode] 198. House Robber 解题报告
- [Leetcode] 198. House Robber 解题报告
- LeetCode-House Robber-解题报告
- 【LeetCode】House Robber 解题报告
- LeetCode-House Robber II-解题报告
- 【LeetCode】House Robber I & II 解题报告
- [leetcode] 213. House Robber II 解题报告
- [leetcode] 337. House Robber III 解题报告
- LeetCode 337. House Robber III 解题报告
- leetcode解题报告:213. House Robber II
- [Leetcode] 213. House Robber II 解题报告
- [Leetcode] 337. House Robber III 解题报告
- [LeetCode]198.House Robber
- 【LeetCode】198. House Robber
- 【LeetCode】198.House Robber
- LeetCode 198. House Robber
- [leetcode] 198.House Robber
- [leetcode] 198. House Robber
- HDU 1532 Drainage Ditches——最大流EK算法
- phpcms v9网站搬家更换域名的方法
- VS调试网站时分析器错误
- 059、060、061-C++
- mac效率工具之moom
- [Leetcode] 198. House Robber 解题报告
- OpenCV学习笔记(23)findContours与drawContours
- java中通过反射获取成员方法并使用
- Ubuntu 14.04 LTS 安装 Virtualenvwrapper
- 使用环信出现的问题
- 单项链表的实现
- HashMap源代码分析
- Python集合基本用法
- latex使用小记录