java 动态规划问题(2)
来源:互联网 发布:dreamweaver调试js 编辑:程序博客网 时间:2024/04/30 12:40
题目:
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; }}
0 0
- java 动态规划问题(2)
- 动态规划 java 石子问题(直线)
- 动态规划之背包问题(JAVA)
- 动态规划问题2
- 动态规划问题2
- java 动态规划 背包问题
- 背包问题-动态规划-JAVA
- 动态规划(java)
- 动态规划-整数划分问题(2)
- 动态规划--01背包问题(2)
- 动态规划-试题(2)-背包问题
- 矩阵连乘问题的动态规划算法(java)
- 动态规划算法求解硬币找零问题(Java)
- 动态规划算法求解硬币找零问题(Java)
- JAVA动态规划(一)--最少硬币找零问题
- 动态规划算法求解硬币找零问题(Java)
- 最长公共子序列问题(Java)-动态规划
- 动态规划求解背包问题(JAVA实现)
- CMTimeMake和CMTimeMakeWithSeconds详解
- PAT-B 1004. 成绩排名
- 手绘作品
- 介绍Android Studio上的几个插件
- Android:控件GridView的使用
- java 动态规划问题(2)
- [LeetCode]RemoveDuplicateLetters解题思路
- 使用单例模式实现自己的HttpClient工具类
- 编译 iperf
- iOS播放音乐与播放系统声音
- 大数据量高并发的数据库优化(转载)
- TableTree4J
- Binding
- 《LeetBook》leetcode题解(17):Letter Combinations of a Phone Number[M]