[leetcode] 213. House Robber II 解题报告
来源:互联网 发布:如何网络恢复mac系统 编辑:程序博客网 时间:2024/05/08 20:38
题目链接:https://leetcode.com/problems/house-robber-ii/
Note: This is an extension of House Robber.
After robbing those houses on that street, the thief has found himself a new place for his thievery so that he will not get too much attention. This time, all houses at this place arearranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, the security system for these houses remain the same as for those in the previous street.
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.
思路:和House Robber题目类似,只是这次有了环形,那么我们可以做两次动归,第一次不抢第一家的钱,则可以抢最后一家的钱。第二次抢第一家的钱,然后就不可以抢最后一家的钱,因此最后把各自最大值比较一下,返回最大的一个即是能够抢到的最多的钱。
时间复杂度为O(n),空间复杂度为O(n)。
代码如下:
class Solution {public: int rob(vector<int>& nums) { if(nums.size()==0) return 0; if(nums.size()==1) return nums[0]; int len = nums.size(); vector<int> dp1(len+1, 0), dp2(len+1, 0); dp1[1] = nums[0]; for(int i=1; i<len-1;i++) dp1[i+1] = max(dp1[i], dp1[i-1]+nums[i]); for(int i=1; i<len; i++) dp2[i+1] = max(dp2[i], dp2[i-1]+nums[i]); return max(dp1[len-1], dp2[len]); }};
- [leetcode] 213. House Robber II 解题报告
- leetcode解题报告:213. House Robber II
- [Leetcode] 213. House Robber II 解题报告
- LeetCode-House Robber II-解题报告
- 【LeetCode】House Robber I & II 解题报告
- LeetCode-House Robber-解题报告
- 【LeetCode】House Robber 解题报告
- [leetcode] 198. House Robber 解题报告
- [leetcode] 337. House Robber III 解题报告
- LeetCode 337. House Robber III 解题报告
- [Leetcode] 198. House Robber 解题报告
- [Leetcode] 337. House Robber III 解题报告
- [leetcode] 213.House Robber II
- LeetCode 213. House Robber II
- [leetcode] 213. House Robber II
- Leetcode - 213. House Robber II
- 213. House Robber II LeetCode
- LeetCode#213. House Robber II
- co 函数库的含义和用法
- 解析assets里的xml文件
- MODBUS ASCII和RTU
- Android IPC机制(一)开启多进程
- iOS 颜色创建
- [leetcode] 213. House Robber II 解题报告
- linux关机命令
- Wince模拟器ActiveSync Remote Display
- OC字符串和数值
- mycat+mysql集群:实现读写分离,分库分表
- Habber - IOS XMPP 客户端 教程 (三)VC始于LoginViewController、、
- TextView设置R.dimen.text_size的值注意
- mongodb适用场景(弊与利)
- Linux下实现数据文件的同步