House Robber[leetcode]题解 c++
来源:互联网 发布:哪个购票软件安全 编辑:程序博客网 时间:2024/05/29 07:28
House Robber
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.
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.
题目大意:在一串正整数串当中取一组整数串,且整数串中的数两两之间不相邻,求得许多串方案当中和最大的串,输出和。
一开始简单以为只是一个判断奇数偶数然后对于一些特殊情况特判一下的情况,后来才发现想当然了,改用动态规划的办法但是也就是递推了一下。
对于数组长度小等于3的特殊处理,数组长度大于3的采用的状态转移方程为:
dp[i] = max(dp[i-2],dp[i-3])+nums[i];
思路:就是以局部最大推导整体最大,需要判断的只是与第i-2的数相加,还是与第i-3的数相加,而第i-4自然不用考虑。
实现c++代码:
#include<cstdio>#include<cstring>#include<string>#include<cstdlib>#include<map>#include<vector>#include<iostream>using namespace std;class Solution {public: int rob(vector<int>& nums) {if(nums.size() == 0){return 0;}if(nums.size() == 1){return nums[0];}if(nums.size() == 2){return max(nums[0],nums[1]);}if(nums.size() == 3){return max(nums[0]+nums[2],nums[1]);}int dp[nums.size()];dp[0] = nums[0];dp[1] = nums[1];dp[2] = nums[0]+nums[2];for(int i = 3;i<nums.size();i++){dp[i] = max(dp[i-2],dp[i-3]) + nums[i];}//注意数组边界问题 return max(dp[nums.size()-3],max(dp[nums.size()-1],dp[nums.size()-2])); }};int main(){vector<int> v;for(int i = 0;i<10;i++){v.push_back(i);}Solution s;cout << s.rob(v)<<endl;return 0;}
- LeetCode House Robber题解
- LeetCode题解:House Robber
- [LeetCode] House Robber 题解
- House Robber[leetcode]题解 c++
- Leetcode题解 198. House Robber
- LeetCode 198. House Robber 题解
- 【LeetCode题解】198. House Robber
- leetcode 198 c++. House Robber
- LeetCode 题解(121): House Robber
- LeetCode 题解(122): House Robber II
- LeetCode题解——House Robber III
- LeetCode 213. House Robber II 题解
- LeetCode 337. House Robber III 题解
- leetcode 213 c++. House Robber II
- Leetcode题解:198.213.337.House Robber套题
- 【dp】Leetcode House Robber&& House Robber II
- 【leetcode】House Robber && House Robber II
- LeetCode --- House Robber & House Robber II
- Android AdapterView
- Nginx配置性能优化
- C++对二进制文件的读写操作
- Mac系统常见的快捷键
- 个人安卓开发调试报错汇总(待补充)
- House Robber[leetcode]题解 c++
- Nginx Rewrite规则初探
- raspberry fm电台
- C++简单版shared_ptr智能指针的实现
- 每个公司、每个社区,都需要不止一个“灵魂人物”。
- Linux kernel 的 sendfile 是如何提高性能的
- Supporting Multiple Screens
- 第三题(1)
- 黑马程序员--集合--4th day