[LeetCode] House Robber II
2015-08-15 11:23
363 查看
This problem is a little tricky at first glance. However, if you have finished the House Robberproblem, this problem can simply be decomposed into two House Robber problems. Suppose there are
Rob houses
Rob houses
The code is as follows. Some edge cases (
nhouses, since house
0and
n - 1are now neighbors, we cannot rob them together and thus the solution is now the maximum of
Rob houses
0to
n - 2;
Rob houses
1to
n - 1.
The code is as follows. Some edge cases (
n <= 2) are handled explicitly.
class Solution { public: int rob(vector<int>& nums) { int n = nums.size(); if (n <= 2) return n ? (n == 1 ? nums[0] : max(nums[0], nums[1])) : 0; return max(robber(nums, 0, n - 2), robber(nums, 1, n -1)); } private: int robber(vector<int>& nums, int l, int r) { int pre = 0, cur = 0; for (int i = l; i <= r; i++) { int temp = max(pre + nums[i], cur); pre = cur; cur = temp; } return cur; } };
相关文章推荐
- Javascript基础(7)DOM简介
- Oracle触发器
- 单片机显示原理(LCD1602)
- text段,data段,bss段,堆和栈
- matlab实现基于DFS的Ford_Fulkerson最大流最小割算法
- 找回回收站图标方法
- HDU 1576 A/B 欧几里德扩展方程
- plupload 批量上传url的修改
- 生活轨迹一期(4.1~8.15)
- Lua学习笔记--环境配置&Hello World
- FTP的搭建与虚拟目录作用<之简单讲解>
- 团中央第一书记参观超级表格
- 设计模式学习笔记-适配器模式
- 起立发言
- 键盘事件
- Javascript基础(6)BOM简介
- A Java Runtime Environment (JRE) or Java Development Kit (JDK) must be available in order to run STS
- 函数返回数组
- 安装Adobe Acrobat 9的时候,有时也会提示缺少pscript.hlp文件
- 微信公众号开发基本接口