LeetCode Algorithms #198 <House Robber>
2016-03-24 15:28
477 查看
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.不偷这家,这家前面相邻那一家为止,前面偷最多钱。 )1,2中多的那一个。
编程实现这个就可以。
解:
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.不偷这家,这家前面相邻那一家为止,前面偷最多钱。 )1,2中多的那一个。
编程实现这个就可以。
解:
class Solution { public: int rob(vector<int>& nums) { if (nums.size() <= 1) return nums.empty() ? 0 : nums[0]; int maxEven = nums[0]; int maxOdd = max(nums[1],nums[0]); for(int idx = 2; idx < nums.size(); idx++) { if(!(idx % 2)) maxEven = max(maxEven + nums[idx], maxOdd); else maxOdd = max(maxOdd + nums[idx], maxEven); } return max(maxEven,maxOdd); } };
相关文章推荐
- 百练:1003:Hangover
- 异常com.google.gson.internal.StringMap cannot cast to..原因&解决方案
- 又一道简单题&&Ladygod(两道思维水题)
- Search gold(dp)
- GOOGLE VR SDK开发VR游戏,VR播放器之二
- django环境搭建
- GOOGLE VR SDK开发VR游戏
- Go语言:通过组合获得接口
- GOOGLE VR SDK开发VR游戏,VR播放器之一
- 【杭电oj】3635 - Dragon Balls(带权并查集,好题)
- GCM(谷歌云推送)客户端服务器端开发全指南(服务器篇)
- 记录一些常用git命令,省得老google
- 【深度学习经典论文翻译2】GoogLeNet-Going Deeper with Convolutions全文翻译
- 安卓智能语音机器人--AlphaGo?你也可以
- django foreign key 自动加_id问题
- PC与串口通信
- 分类(类别,category),类扩展
- How much common sense have YOU got? Take the test
- sth about kmp
- lightoj 1057 - Collecting Gold 状压DP求解TSP