#leetcode#198. House Robber
2016-04-27 16:58
267 查看
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+1个房子,i+2个房子,第i+2个房子的收益为i个房子+第i+2个房子与i+1个房子中的较大者
精简代码,没必要去维护一个数组,只需要维护两个变量即可class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
if(n<=0) return 0;
int best=0;
int bestnow=0;
bestnow=nums[0];
if(n==1) return bestnow;
int i;
for(i=1;i<n;i++)
{
int temp=bestnow;
bestnow=((best+nums[i])>bestnow)?(best+nums[i]):bestnow;
best=temp;
}
return bestnow;
}
};
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+1个房子,i+2个房子,第i+2个房子的收益为i个房子+第i+2个房子与i+1个房子中的较大者
class Solution { public: int rob(vector<int>& nums) { int n=nums.size(); if(n<=0) return 0; int ans ; ans[0]=nums[0]; if(n==1) return ans[0]; ans[1]=(nums[0]>nums[1])?nums[0]:nums[1]; if(n==2) return ans[1]; int i; for(i=2;i<n;i++) { int robn=ans[i-2]+nums[i]; ans[i]=(robn>ans[i-1])?robn:ans[i-1]; } return ans[n-1]; } };
精简代码,没必要去维护一个数组,只需要维护两个变量即可class Solution {
public:
int rob(vector<int>& nums) {
int n=nums.size();
if(n<=0) return 0;
int best=0;
int bestnow=0;
bestnow=nums[0];
if(n==1) return bestnow;
int i;
for(i=1;i<n;i++)
{
int temp=bestnow;
bestnow=((best+nums[i])>bestnow)?(best+nums[i]):bestnow;
best=temp;
}
return bestnow;
}
};
相关文章推荐
- jqGrid的treegrid的bug修复
- 对嵌入式Linux中的根文件系统的理解和解析
- git Pull Request 是什么意思?
- linux 利用nethogs查看某进程的网卡流量
- Tiled GPU perf. warning: Backbuffer was not cleared/discarded, doing Render.OpaqueGeometry/RenderFor
- 使用javah生成jni文件(命令行命令)
- struts2集合
- CakePHP程序员必须知道的21条技巧
- nginx反向代理到后端tomcat,并将IP地址发送到后端的配置
- Java常见错误-“Dynamic Web Module 3.0 requires Java 1.6 or newer.”错误
- nrf51822 --- 微信移植 (官方例子移植到SDK10.0)
- SQL Server之——JDBC 到主机 的 TCP/IP 连接失败
- IO 流之管道流
- 【基础】SublimeText编写MarkDown文档
- Android学习笔记——XML解析
- 个人工作总结9
- 微信网页动画---swiper.animate.css
- IO多路复用之select、poll、epoll详解
- 修改输入框placeholder文字默认颜色-webkit-input-placeholder方法
- ASP.NET MVC数组模型绑定详解