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.
Example 1:
Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: [2,7,9,3,1] Output: 12 Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1). Total amount you can rob = 2 + 9 + 1 = 12.
解答:
纯递归:
class Solution {
public int rob(int[] arr) {
return search(arr,arr.length-1);
}
public int search(int[] arr,int index){
if(index < 0)
return 0;
else{
int a = arr[index] + search(arr,index - 2);
int b = search(arr,index - 1);
return Math.max(a,b);
}
}
}
先保存已计算值,再递归:
Mine:
class Solution {
public static int[] f = new int[1000];
public int rob(int[] nums) {
for(int i = 0;i < f.length;++i){
f[i] = -1;
}
return search(nums, nums.length-1);
}
public int search(int[] nums,int index){
if(index < 0)
return 0;
if(f[index] >= 0)
return f[index];
else{
int a = nums[index] + search(nums,index - 2);
int b = search(nums,index - 1);
f[index] = Math.max(a, b);
return f[index];
}
}
}
Better Solution:
class Solution {
public int rob(int[] arr) {
if(arr.length <= 2){
if(arr.length == 2){
return Math.max(arr[0], arr[1]);
}
if(arr.length == 1){
return arr[0];
}
if(arr.length == 0) {
return 0;
}
//return Math.max(arr[0],arr[1]);
}
arr[2] = Math.max(arr[2], arr[2] + arr[0]);
for(int i = 3; i < arr.length; i++) {
int max = arr[i];
int n = Math.max(arr[i] + arr[i-2], arr[i] + arr[i-3]);
arr[i] = Math.max(max,n);
}
return Math.max(arr[arr.length - 1], arr[arr.length - 2]);
}
}