题目:
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.
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases. Also thanks to @ts for adding additional test cases.
链接: http://leetcode.com/problems/house-robber/
2/22/2017, Java
看了提示决定用DP,但是好像写法麻烦了很多,并且用了2个数组。performance很差
1 public class Solution { 2 public int rob(int[] nums) { 3 if (nums.length == 0) return 0; 4 if (nums.length == 1) return nums[0]; 5 if (nums.length == 2) return Math.max(nums[0], nums[1]); 6 if (nums.length == 3) return Math.max(nums[0] + nums[2], nums[1]); 7 8 int[] f = new int[nums.length]; 9 int[] g = new int[nums.length]; 10 11 f[0] = nums[0]; 12 g[0] = 0; 13 f[1] = 0; 14 g[1] = nums[1]; 15 f[2] = nums[0] + nums[2]; 16 g[2] = nums[2]; 17 18 for(int i = 3; i < nums.length; i++) { 19 f[i] = nums[i] + Math.max(f[i - 2], g[i - 2]); 20 g[i] = nums[i] + Math.max(f[i - 3], g[i - 3]); 21 } 22 23 return Math.max(Math.max(f[nums.length - 1], g[nums.length - 1]), Math.max(f[nums.length - 2], g[nums.length - 2])); 24 } 25 }
别人的DP略简单,原因是:其实每一步的值要么是前一个元素时抢的钱,或者是当前元素的钱+前两个元素抢的钱,这样就可以简化成一个数组。
还有更简单不需要额外数组的方法,留给二刷
7/16/2017
做到House Robber II重新写一下O(1) space的做法
1 public class Solution { 2 public int rob(int[] nums) { 3 int robLast = 0, notRobLast = 0, maxMoney = 0; 4 for (int i = 0; i < nums.length; i++) { 5 maxMoney = Math.max(robLast, notRobLast + nums[i]); 6 notRobLast = robLast; 7 robLast = maxMoney; 8 } 9 return maxMoney; 10 } 11 }