java 动态规划问题(2)
2016-04-27 11:51
681 查看
题目:
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家时所偷的金钱最大额为temp[i],则有如下关系:
算法如下:
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家时所偷的金钱最大额为temp[i],则有如下关系:
temp[i] = max(temp[i-1],temp[i-2]+nums[i]);
算法如下:
public class Solution { public int rob(int[] nums) { if(nums==null||nums.length==0) return 0; if(nums.length==1) return nums[0]; if(nums.length==2) return max(nums[0],nums[1]); int[] temp = new int[nums.length]; temp[0] = nums[0]; temp[1] = max(nums[0],nums[1]); for(int i=2;i<temp.length;i++){ temp[i] = max(temp[i-1],temp[i-2]+nums[i]); } return temp[temp.length-1]; } public int max(int a,int b){ return a>b?a:b; } }
相关文章推荐
- eclipse查看jar源码
- Java 正则表达式
- java新手学习
- [selenium webdriver Java]元素定位——findElement/findElements
- Java基础学习总结(54)——JSON和Map转换的工具类
- Java基础学习总结(54)——JSON和Map转换的工具类
- Java基础学习总结(54)——JSON和Map转换的工具类
- 【java线程系列】java线程系列之java线程池详解
- 【java线程系列】java线程系列之java线程池详解
- Eclipse格式化失效的配置
- 全面分析 Spring 的编程式事务管理及声明式事务管理(转)
- Java---练习:文件切割与合并(1)
- Java---练习:文件切割与合并(1)
- java 中的Set,List,Map
- Java 文件和byte数组转换
- spring框架学习(一)
- Java协变数组和类型擦除
- RxJava----操作符:条件和布尔操作符
- Spring整合Proxool到Ibatis中
- 《疯狂Java讲义(第3版)》.(李刚)——数组