(java)House Robber
2015-12-05 16:39
369 查看
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.
思路:本题是一个典型的动态规划题目,设置一个dp[i]记录到第i家时强盗可以抢到的最大钱数。根据题意,可以得出dp的递归式
dp[0]=nums[0],dp[1]=max(nums[0],nums[1])
dp[i]= max(dp[i-2]+nums[i],dp[i-1]);
代码如下(已通过leetcode)
public class Solution {
public int rob(int[] nums) {
int length=nums.length;
if(length==0) return 0;
if(length==1) return nums[0];
if(length==2) return nums[0]>nums[1]?nums[0]:nums[1];
int[] dp=new int[length];
dp[0]=nums[0];
dp[1]=Math.max(nums[0], nums[1]);
for(int i=2;i<length;i++)
dp[i]=Math.max(dp[i-2]+nums[i], dp[i-1]);
return dp[length-1];
}
}
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.
思路:本题是一个典型的动态规划题目,设置一个dp[i]记录到第i家时强盗可以抢到的最大钱数。根据题意,可以得出dp的递归式
dp[0]=nums[0],dp[1]=max(nums[0],nums[1])
dp[i]= max(dp[i-2]+nums[i],dp[i-1]);
代码如下(已通过leetcode)
public class Solution {
public int rob(int[] nums) {
int length=nums.length;
if(length==0) return 0;
if(length==1) return nums[0];
if(length==2) return nums[0]>nums[1]?nums[0]:nums[1];
int[] dp=new int[length];
dp[0]=nums[0];
dp[1]=Math.max(nums[0], nums[1]);
for(int i=2;i<length;i++)
dp[i]=Math.max(dp[i-2]+nums[i], dp[i-1]);
return dp[length-1];
}
}
相关文章推荐
- java BigDecimal介绍
- 安卓JNI--JNI底层C回调Java方法
- JAVA通信编程(四)——UDP通讯
- JAVA通信编程(四)——UDP通讯
- Java的Spring框架中bean的继承与内部bean的注入
- 《疯狂JAVA讲义》——Singleton类
- Java对象创建之new关键字和newinstance()方法
- AES算法 Java实现
- maven 3.3.3 + MyEclipse2015 for windows 配置
- Java内存管理机制
- JAVA JTextField 和JTextArea的一般方法
- Java类-Stack的学习
- 转载:Java使用dom4j解析XML
- JAVA读取文件中存在BOM的问题
- c#调用JAVA提供的WebService处理日期格式
- java内存泄露和调优
- Java静态类使用Bean
- java 归并排序
- 详解Java的Spring框架中bean的定义以及生命周期
- SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)