LeetCode 213. House Robber II
为什么这样行
class Solution {
public int rob(int[] nums) {
if(nums == null || nums.length == 0) return 0;
if(nums.length == 1) return nums[0];
//the core idea is, we can divide this problem as the one that contains the first but not contains the last and contains the last but not contains the first, then those two is the same principle.
return Math.max(rob(nums, 0, nums.length - 2), rob(nums, 1, nums.length - 1));
}
private int rob(int[] nums, int start, int end) {
int n = end - start + 1;
int[] dp = new int[n+1]; //we have to use length of n+1 instaed of n, so dp[i] represent for we only have first ith house
dp[0] = 0;//
dp[1] = nums[start];
for(int i = 2; i<= n; i++) {
dp[i] = Math.max(dp[i-2] + nums[start++], dp[i-1]);
}
return dp[n];
}
}
这样就不行了?
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 Math.max(nums[0], nums[1]);
return Math.max(rob(nums, 0, nums.length - 2), rob(nums, 1, nums.length - 1));
}
private int rob(int[] nums, int s, int e) {
if (e-s+1 == 1) return nums[s];
if (e-s+1 == 2) return Math.max(nums[s], nums[s+1]);
int[] dp = new int[e-s+1];
dp[0] = nums[s];
dp[1] = Math.max(nums[s], nums[s+1]);
for (int i = s + 2; i <= e; i++) {
dp[i-s] = Math.max(dp[i-s-2] + nums[s], dp[i-s-1]);
}
return dp[e-s];
}
}

浙公网安备 33010602011771号