leetcode 198. House Robber
2017-08-18 17:24
447 查看
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题。
dp[i][1] means we rob the current house(i-1 house) and dp[i][0] means we don't,
so it is easy to convert this to O(1) space.
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题。
public int rob(int[] nums) { int n=nums.length; if(n==0){ return 0; } //dp[i]:存储i~num.length能偷的最大钱 int[] dp=new int[n+1]; dp =0; dp[n-1]=nums[n-1]; for(int i=n-2;i>=0;i--){ //不偷i,再从i+1开始偷,或者偷i,再从i+2开始偷 dp[i]=Math.max(dp[i+1], nums[i]+dp[i+2]); } return dp[0]; }大神也用的DP,不过跟我的有点不一样。
public int rob(int[] num) { int[][] dp = new int[num.length + 1][2]; for (int i = 1; i <= num.length; i++) { dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]); dp[i][1] = num[i - 1] + dp[i - 1][0]; } return Math.max(dp[num.length][0], dp[num.length][1]); }
dp[i][1] means we rob the current house(i-1 house) and dp[i][0] means we don't,
so it is easy to convert this to O(1) space.
public int rob(int[] num) { //max monney can get if rob current house int rob = 0; //max money can get if not rob current house int notrob = 0; for(int i=0; i<num.length; i++) { //if rob current value, previous house must not be robbed int currob = notrob + num[i]; //if not rob ith house, take the max value of robbed (i-1)th house and not rob (i-1)th house notrob = Math.max(notrob, rob); rob = currob; } return Math.max(rob, notrob); }
相关文章推荐
- [LeetCode]198. House Robber (JavaScript)
- LeetCode -- 198. House Robber
- LeetCode 198. House Robber
- LeetCode:198. House Robber
- leetcode 198. House Robber
- LeetCode 198. House Robber
- leetcode198. House Robber
- LeetCode 198. House Robber
- leetcode 198. House Robber
- LeetCode 198. House Robber
- leetcode 198. House Robber
- 2017.12.18 LeetCode - 198. House Robber【dp入门】
- LeetCode198. House Robber
- Leetcode-198. House Robber
- leetcode 198. House Robber
- Leetcode——198. House Robber
- LeetCode-198. House Robber (JAVA)寻找数组不相邻组合最大值DP
- Leetcode:198. House Robber(week 9)
- LeetCode-198. House Robber
- LeetCode 198. House Robber