[leetcode] 198. House Robber
来源:互联网 发布:java短链接实现 编辑:程序博客网 时间:2024/06/05 03:34
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.
本质是在一组数组中选取不相邻的元素,使其和最大。考虑是Dynamic Programming来解。维护一个数组dp,dp[i]代表到位置i时,不相邻元素的最大和。很容易得到一个递推公式:dp[i] = max(nums[i]+dp[i-2], dp[i-1]). dp的初始化使用nums[0]和nums[1]即可。
解法一:
class Solution {public: int rob(vector<int>& nums) { if (nums.size() == 0) return 0; else if (nums.size() == 1) return nums[0]; vector<int> dp = {nums[0],max(nums[0],nums[1])}; for(int i = 2; i < nums.size(); i++){ dp.push_back(max(nums[i]+dp[i-2],dp[i-1])); } return dp.back(); }};
或者考虑维护两个变量a和b,分别表示到奇偶位置的时候,不相邻元素之和最大。那么
解法二:
class Solution {public: int rob(vector<int>& nums) { int a = 0, b = 0; for(int i = 0; i < nums.size(); i++){ if (i%2==0){ a = max(a + nums[i], b); }else{ b = max(a, b + nums[i]); } } return max(a,b); }};
0 0
- [LeetCode]198.House Robber
- 【LeetCode】198. House Robber
- 【LeetCode】198.House Robber
- LeetCode 198. House Robber
- [leetcode] 198.House Robber
- [leetcode] 198. House Robber
- LeetCode:198. House Robber
- 198. House Robber LeetCode
- [LeetCode]198. House Robber
- LeetCode || 198. House Robber
- LeetCode-198. House Robber
- [LeetCode]198. House Robber
- 【LeetCode】198. House Robber
- LeetCode#198. House Robber
- LeetCode 198. House Robber
- leetcode 198. House Robber
- LeetCode *** 198. House Robber
- leetcode 198. House Robber
- 【9404】最大公约数
- Oracle 行转列 wm_concat函数
- 大数运算c++
- 7.15~7.17GDOI模拟赛总结
- c++之STL string(2)复制,迭代,连接,查找,截短,字符串反转,大小写转换
- [leetcode] 198. House Robber
- Android消息处理机制(Handler、Looper、MessageQueue与Message)
- JZOJ.1758 过河
- [暴力] HDU 4473 Exam
- python学习——常用第三方模块PIL
- 3.2 (N)UMA模型的内存组织
- android五大布局之-RelativeLayout
- UVa230 Borrowers
- js鼠标事件中的clientX/clientY,screenX/screenY,pageX/pageY,offsetX/offsetY,layerX/layerY,x/y