House Robber II
来源:互联网 发布:数据库安全防护总结 编辑:程序博客网 时间:2024/06/03 15:39
题目
原题
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.
思路
这道题是House Robber(链接:https://leetcode.com/problems/house-robber/)的升级版本.即所给定的nums构成了环.由于每个house最多被rob一次, 设len=nums.size(),所以这个环只对nums[0]和nums[len-1]起作用.即如果选择了nums[0], 就不能选择了nums[len-1];如果选择了nums[len-1], 就不能选择nums[0].所以该问题就变了了House Robber的两个子问题的结果最大值.ans=max(rob(nums[0,...,len-2), rob(nums[1,...,len-1)). 其中rob为House Robber问题的解.具体看代码.
code
class Solution {public: int rob_helper(const vector<int>& nums, const int s, const int e) { int len = e - s + 1; vector<int>res(len, 0); res[0] = nums[s]; res[1] = max(nums[s], nums[s + 1]); for(int i = s + 2; i <= e; i++) { res[i - s] = max(res[i - s - 2] + nums[i], res[i - s - 1]); } return res[len - 1]; } int rob(vector<int>& nums) { int len = nums.size(); if(len <= 0) return 0; if(len <= 1) return nums[0]; // Include the first one of nums without the last one. int f = rob_helper(nums, 0, len - 2); // Include the last one of nums without the first int s = rob_helper(nums, 1, len - 1); return max(f, s); }};
0 0
- LeetCode House Robber II
- 213House Robber II
- Leetcode213-House Robber II
- [LeetCode] House Robber II
- [leetcode] House Robber II
- 【leetcode】House Robber II
- House Robber II
- Leetcode: House Robber II
- House Robber II
- House Robber II
- leetcode House Robber II
- [leetcode] House Robber II
- LeetCode213:House Robber II
- [LeetCode]House Robber II
- House Robber II
- leetcode--House Robber II
- leetcode House Robber II
- House Robber II
- 添加core 服务和app 服务 root 权限执行
- POJ1987(树分治)
- update-alternatives
- PHP知识点小记
- 64位Win7 IIS报 CS0016错误 解决办法
- House Robber II
- VTK+cmake+vs2008安装和编译,学习笔记
- spring mvc 接收返回json串
- Spring4新特性——集成Bean Validation 1.1(JSR-349)到SpringMVC
- Linux 文件和目录的属性
- UVA - 10881-Piotr's Ants-思路题/模拟
- Matlab2014b 并行运算开启方法
- 从校园到工作的路(四)——关于linux的一些基本知识
- iOS导航栏背景色,去掉边界黑线,去掉搜索框的边界黑线和其中文本输入框的阴影