题目描述:
抢劫一排住户,但是不能抢邻近的住户,求最大抢劫量。
解决思路和代码:
package DP;
import java.util.Arrays;
public class _198_rob {
private static int rob1(int[] nums, int i){
if (i < 0){
return 0;
}
return Math.max(rob1(nums, i-2) + nums[i], rob1(nums, i-1));
}
public static int rob1(int[] nums){
return rob1(nums, nums.length-1);
}
public static int rob2(int[] nums){
int n = nums.length;
int[] mem = new int[n+1];
Arrays.fill(mem, -1);
return rob2(nums, n-1, mem);
}
private static int rob2(int[] nums, int i, int[] mem){
if (i < 0){
return 0;
}
if (mem[i] >= 0){
return mem[i];
}
int res = Math.max(rob1(nums, i-2) + nums[i], rob1(nums, i-1));
mem[i] = res;
return res;
}
public static int rob(int[] nums){
int n = nums.length;
int[] dp = new int[n];
dp[0] = nums[0];
dp[1] = Math.max(nums[0], nums[1]);
for (int i = 2; i < n; i++){
dp[i] = Math.max(dp[i-2] + nums[i], dp[i-1]) ;
}
return dp[n-1];
}
public static void main(String[] args) {
int[] nums = {2, 7, 9, 3, 1};
int[] nums2 = {2, 1, 1, 2};
System.out.println(rob2(nums2));
}
}