198. House Robber
2016-03-28 23:42
267 查看
1.Question
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.
2.Code
3.Note
a.
这类问题应该想到DP。DP的关键是,找到状态 和 状态转移方程,一般会有一个或多个初始状态,而状态转移方程一般都能由递归方程写出。这个题的本质是,从一个数组中选择一些元素,使其和最大,而这个元素选择的约束条件是两两不能相邻。我们根据题意,可以想到DP的状态转移方程dp[i] = max(nums[i]+dp[i-2], dp[i-1])。
b.关于vector,还要熟悉一些常用的成员函数。
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.
2.Code
class Solution { public: int rob(vector<int>& nums) { if(nums.empty()) return 0; if(nums.size() == 1) return nums[0]; vector<int> count(nums.size()); count[0] = nums[0]; count[1] = max(nums[0], nums[1]); for(int i = 2; i < nums.size(); i++) count[i] = max(nums[i] + count[i-2], count[i-1]); return count.back(); } };
3.Note
a.
这类问题应该想到DP。DP的关键是,找到状态 和 状态转移方程,一般会有一个或多个初始状态,而状态转移方程一般都能由递归方程写出。这个题的本质是,从一个数组中选择一些元素,使其和最大,而这个元素选择的约束条件是两两不能相邻。我们根据题意,可以想到DP的状态转移方程dp[i] = max(nums[i]+dp[i-2], dp[i-1])。
b.关于vector,还要熟悉一些常用的成员函数。
v.empty() | 判断v是否为空 |
v.size() | 返回v的size |
v.begin() | 返回vector容器中起始元素的迭代器 |
v.end() | 返回vector容器中末尾元素的后一个地址 |
v.front() | 返回vector容器中起始元素的值 |
v.back() | 返回vector容器中末尾元素的值 |
v.push_back(elem) | 插入一个elem到容器的末尾 |
v.pop_back() | 弹出容器末尾的值 |
相关文章推荐
- MoKee OpenSource项目介绍及开发流程
- struts2中ognl表达式%$#在jsp页面的使用总结以及<s:a title=%{title}>的作用
- Xen启动过程分析(还是分享过来吧,找了好长时间)
- Spring Bean的生命周期管理方法
- 79. Word Search
- hadoop生态系统学习之路(三)java实现上传文件(本地或ftp)至hdfs
- 快速排序算法
- POJ 1064 切绳子 二分搜索求一个可行解
- ES6学习小计
- 拉格朗日乘子法(编辑中)
- Eclipse默认字体CourierNew
- 重写equals 方法
- [Think In Java]基础拾遗4 - 并发
- NY145 聪明的小柯
- 又被拒了,心情不好
- Emmet
- 进程间通信之-信号量semaphore--linux内核剖析(十)
- LeetCode 231 Power of Two(三解)
- 无线键盘的安全性分析与探究
- StatePattern