LeetCode之旅(22)-House Robber
2016-04-05 14:41
288 查看
题目:
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.
思路:
本质是求一个非负整数数组a【n】的非相邻元素的最大和。这一类问题要用动态规划的思路,把数组的长度,作为每一步。设置数组count【n】作为数组的每一步的最大的和。存在推倒关系:count【n】 = max(count【n-1】,(count【n-2】+a【n】));
-
代码:
public class Solution { public int rob(int[] nums) { int[] count = null; int n = nums.length; if(n == 0){ return 0; } if(n == 1){ return nums[0]; } if(n > 1){ count = new int ; } count[0] = nums[0]; if(nums[1] > nums[0]){ count[1] = nums[1]; }else{ count[1] = nums[0]; } for(int i = 2;i < n;i++){ if((count[i-2]+nums[i]) > count[i-1]){ count[i] = count[i-2]+nums[i]; }else{ count[i] = count[i-1]; } } return count[n-1]; } }
相关文章推荐
- LeetCode之旅(22)-House Robber
- String str = "a"+"b"+"c"+"d";一共创建了几个对象?
- Java面试题大全(一)
- CentOS 7 / Ubuntu 15.04 上安装 PHP Laravel 过程详解
- 《构建之法》第四章读后感--软件工程
- hdu 2602 Bone Collector 01背包模板
- Shiro源码分析之两种Session的方式
- SELinux深入理解
- Linux之lsof命令
- OS X 下 Sublime Text 3常见问题的解决
- Android SDK代理资源收集
- Spring导入多个独立的 .properties配置文件
- 换行符与回车符
- JVM Stack和Heap、GC
- @protocol 的实现的细节
- windows下JAVA开发操作hadoop的方法
- 基于.NET平台常用的框架整理
- CSS-硬件加速
- JPA中@JoinTable和@JoinColumn注解的使用
- 《人人都爱经济学》 读书笔记(1)