[leetcode] 213.House Robber II
2015-07-27 22:12
459 查看
题目:
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 are arranged 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.
题意:
这道题是198题的延续,/article/9676029.html。不过这道题加了一个条件,就是首尾的房子也当作是相邻的。所以其实可以把环断开,因为首尾的房子最多只有一个在最终答案里。所以我们可以分成第一个房子到倒数第二个房子,或者第二个房子到最后一个房子。分别使用198题的动态规划的方法,找出较大者。
以上。
代码:
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 are arranged 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.
题意:
这道题是198题的延续,/article/9676029.html。不过这道题加了一个条件,就是首尾的房子也当作是相邻的。所以其实可以把环断开,因为首尾的房子最多只有一个在最终答案里。所以我们可以分成第一个房子到倒数第二个房子,或者第二个房子到最后一个房子。分别使用198题的动态规划的方法,找出较大者。
以上。
代码:
class Solution { public: int rob(vector<int>& nums) { if(nums.size() == 0)return 0; else if(nums.size() == 1)return nums[0]; return max(rob(nums,0, nums.size() - 1), rob(nums, 1, nums.size())); } int rob(vector<int>& nums, int start, int end) { if(end == start + 1)return nums[start]; vector<int> DP(end - start, 0); DP[0] = nums[start]; DP[1] = max(nums[start], nums[start + 1]); for(int i = start + 2; i < end; i++) { DP[i - start] = max(DP[i - start - 1], DP[i - start - 2] + nums[i]); } return DP[end - start - 1]; } };
相关文章推荐
- 整数排序
- HashMap,LinkedHashMap,TreeMap的区别
- 一刀斩:SVN客户端访问URL失败--请求的名称有效,但是找不到请求的类型
- mysql 存储过程时间月份减法
- 内存管理
- php编程冒泡排序
- MyBatis知多少(20)MyBatis读取操作
- Tomcat服务器在Mac平台和windows平台上的搭建
- 莫比乌斯反演
- free delete malloc new(——高品质量程序设计指南第16章)
- 平衡二叉树
- cuDNN: efficient Primitives for Deep Learning 论文阅读笔记
- [3D游戏开发]Early ZBuffer
- UI中 View、Label的方法
- 产生冠军
- KnockoutJS的使用及分析
- HDU 1233 首字母变大写
- LeetCode Everyday --226
- Linux系统调用及用户编程接口(API)
- 程序员必读的六本书