博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] House Robber II
阅读量:4606 次
发布时间:2019-06-09

本文共 1055 字,大约阅读时间需要 3 分钟。

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 n houses, since house 0 and n - 1 are now neighbors, we cannot rob them together and thus the solution is now the maximum of

  1. Rob houses 0 to n - 2;
  2. Rob houses 1 to n - 1.

The code is as follows. Some edge cases (n <= 2) are handled explicitly.

1 class Solution { 2 public: 3     int rob(vector
& nums) { 4 int n = nums.size(); 5 if (n <= 2) return n ? (n == 1 ? nums[0] : max(nums[0], nums[1])) : 0; 6 return max(robber(nums, 0, n - 2), robber(nums, 1, n -1)); 7 } 8 private: 9 int robber(vector
& nums, int l, int r) {10 int pre = 0, cur = 0;11 for (int i = l; i <= r; i++) {12 int temp = max(pre + nums[i], cur);13 pre = cur;14 cur = temp;15 } 16 return cur;17 }18 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4732035.html

你可能感兴趣的文章
flask模板应用-空白控制 --
查看>>
学习过程笔记 7月上
查看>>
ASP.NET WebAPI String 传值问题
查看>>
【2017-3-1】冒泡排序
查看>>
[转载]后缀数组算法总结
查看>>
pandas数据结构练习题(部分)
查看>>
NOI2016 区间 【线段树】
查看>>
第二阶段团队绩效评估
查看>>
.net第三方数据库物理卡号同步功能实现
查看>>
机器学习02_逻辑回归作业(附加)
查看>>
zstu.4189: 逻辑运算(构建 && 前缀表达式入门)
查看>>
iOS中常见的自定义宏
查看>>
Android中Context详解 ---- 你所不知道的Context
查看>>
8.存储过程和触发器
查看>>
NOIP模拟题——LGTB与桌子
查看>>
64位Navicat Premium安装/破解【含资源】
查看>>
事件查看器常见ID代码解释
查看>>
使用mdf和ldf附加还原SQL Server数据文件
查看>>
python函数
查看>>
Python美味食谱:1.7 将字符串逐字符或逐词反转
查看>>