198. House Robber(入室强盗)
来源:互联网 发布:矩阵论教程 pdf 编辑:程序博客网 时间:2024/04/29 01:08
标签(空格分隔): leetcode dp
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
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.
题意:
1. 每间房屋藏有一定的钱
2. 阻止你们抢劫每个人的唯一约束是邻近的房屋有安全系统连接,
3. 如果两个相邻的房屋在同一天晚上被打破,它将自动联系警察。
4. 给出一个代表每个房子的非负整数的钱的列表,确定你今天晚上可以抢救的最大金额,而不用警报。
思路;
状态转移方程:
dp[0] = num[0] (当i=0时)
dp[1] = max(num[0], num[1]) (当i=1时)
dp[i] = max(num[i] + dp[i - 2], dp[i - 1]) (当i !=0 and i != 1时)
当数只有0,1,2这大小的时候,直接计算,然后如果大于2个数,我们就可以分解成三部分,每次计算最左边最大值和最右边的数的和与中间的最大值比较;
int rob(vector<int>& nums) { if (nums.empty()){return 0;} int len = nums.size(); if (len == 1) return nums[0]; if (len == 2) return nums[0]>nums[1]?nums[0]:nums[1]; int i = 2; int ans = 0; int left = nums[0], mid = max(nums[0],nums[1]); for (i; i < len;++i) { ans = max(nums[i] +left, mid); left = mid; mid = ans; } return ans;}
别人的做法:
class Solution {public: int rob(vector<int>& nums) { int numsSize = nums.size(); int a = 0, b = 0; for(int i=0; i<numsSize; i++){ if(i%2==0) a = max(a+nums[i],b); else b = max(b+nums[i],a); } return max(a,b); }};
设置奇偶校验,交替计算前n项的最大值;
- 198. House Robber(入室强盗)
- leetcode 198. House Robber 入室抢劫 + DP动态规划求解
- LeetCode 198 House Robber(强盗盗窃最大值)(动态规划)(*)
- 198. House Robber (Easy)
- 337. House Robber III+198. House Robber
- 198. House Robber&&213. House Robber II
- 198. House Robber && 213. House Robber II
- 198. House Robber(C++实现)
- LeetCode 198. House Robber(小偷游戏)
- 198. House Robber (房屋盗窃)
- 198. House Robber (简单dp)
- LeetCode 198. House Robber(Python)
- [LeetCode]198.House Robber
- 【LeetCode】198. House Robber
- 【LeetCode】198.House Robber
- LeetCode 198. House Robber
- 198.House Robber
- [leetcode] 198.House Robber
- BZOJ 1711 浅谈网络流大水题
- matlab2c使用c++实现matlab函数系列教程-ones函数
- Qt实现实时曲线
- 面试题:null == undefined ?以及object.is()区别
- hadoop 经典入门wordcount
- 198. House Robber(入室强盗)
- ros学习笔记3
- Python中的map()函数和reduce()函数的用法
- maven 下载及配置
- 归并排序和快速排序的衍生问题(二)
- 框架制作淘宝注册表--不掺杂任何CSS
- 【shell实例】一键自动化pull->更新文件->commit->压缩打包->上传服务器
- [bzoj4976]宝石镶嵌
- BZOJ 1477 青蛙的约会 [扩展欧几里得]