LeetCode 198. House Robber
2016-04-05 02:12
399 查看
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.
题目:你是一个非常牛逼的强盗,计划抢一条街。每个屋子里面都存有一定数量的钱,唯一制约你抢钱的原因是:相邻的屋子的安全系统是相连的,如果在同一个晚上,两个相邻的屋子被闯入了,安全系统会自动的报警。
求解你不惊动警察,能抢多少钱
这个题目是典型的动态规划,第i次决定是否抢钱,要看是前i-2个屋子里面能抢到的最多的钱与第i个屋子的钱之和是否大于前i-1个屋子里能抢到的最多的钱!
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.
题目:你是一个非常牛逼的强盗,计划抢一条街。每个屋子里面都存有一定数量的钱,唯一制约你抢钱的原因是:相邻的屋子的安全系统是相连的,如果在同一个晚上,两个相邻的屋子被闯入了,安全系统会自动的报警。
求解你不惊动警察,能抢多少钱
这个题目是典型的动态规划,第i次决定是否抢钱,要看是前i-2个屋子里面能抢到的最多的钱与第i个屋子的钱之和是否大于前i-1个屋子里能抢到的最多的钱!
class Solution { public: //辅助函数,用来取出较大的数 int max(int a, int b) { return a > b ? a : b; } int rob(vector<int>& nums) { //建立一个长度为n的向量,第i-1位用来保存前i家可以抢到的最多的钱 vector<int> money(nums.size(), 0); if (0 == nums.size())return 0; if (1 == nums.size())return nums[0]; else { money[0] = nums[0]; money[1] = max(nums[0], nums[1]); for (unsigned int i = 2;i < nums.size();++i) //得出前i家可以抢到的最多的钱 money[i] = max(nums[i] + money[i - 2], money[i - 1]); } return money[nums.size() - 1]; } };
相关文章推荐
- 241. Different Ways to Add Parentheses
- 用OpenInventor实现的NeHe OpenGL教程-第三十五课
- 2016CampDay7problemF.Frank Sinatra
- 用OpenInventor实现的NeHe OpenGL教程-第三十三课
- 用OpenInventor实现的NeHe OpenGL教程-第三十四课
- 用OpenInventor实现的NeHe OpenGL教程-第三十二课
- 主成分分析与隐变量模型
- 用OpenInventor实现的NeHe OpenGL教程-第三十课
- 用OpenInventor实现的NeHe OpenGL教程-第三十一课
- Redis哨兵(sentinel)
- 用OpenInventor实现的NeHe OpenGL教程-第二十九课
- 用OpenInventor实现的NeHe OpenGL教程-第二十七课
- 用OpenInventor实现的NeHe OpenGL教程-第二十八课
- 用OpenInventor实现的NeHe OpenGL教程-第二十五课
- 用OpenInventor实现的NeHe OpenGL教程-第二十六课
- 用OpenInventor实现的NeHe OpenGL教程-第二十三课
- 用OpenInventor实现的NeHe OpenGL教程-第二十四课
- 基数排序(RedixSort)
- JDK动态代理实现原理
- 用OpenInventor实现的NeHe OpenGL教程-第二十二课