House Robbery Series
House robbery
Problem Description
Problem Analysis-Dynamic Planning
Status: The current maximum amount of cash that can be obtained
Choice: Choose this house
or not dp_i = max (do not choose this house, choose this house)=max(dp_i_1,dp_i_2+nums[i]);
class Solution {
public int rob(int[] nums) {
int dp_i=0;
int dp_i_1=0;
int dp_i_2=0;
//dp_i表示当前i之后的最大值,从后往前推
for(int i=nums.length-1;i>=0;i--){
dp_i = Math.max(dp_i_1,nums[i]+dp_i_2);
dp_i_2=dp_i_1;
dp_i_1=dp_i;
}
return dp_i;
}
}
House Robbery II
Problem Description:
Problem analysis: The first house and the last house cannot appear at the same time, and the rest are the same as above;
public int rob(int[] nums) {
if(nums.length==0)return 0;
if(nums.length==1)return nums[0];
return Math.max(rob(nums,0,nums.length-2),rob(nums,1,nums.length-1));
}
public int rob(int []nums,int strat,int end){
int dp_i=0,dp_i_1=0,dp_i_2=0;
for(int i=end;i>=strat;i--){
dp_i = Math.max(dp_i_1,nums[i]+dp_i_2);
dp_i_2 = dp_i_1;
dp_i_1 = dp_i;
}
return dp_i;
}
}
House Robber III
Problem description
Problem analysis:
class Solution {
public int rob(TreeNode root) {
//设一个长度为2的数组res,res[0]表示不抢该节点,res[1]表示抢该节点
int res[]=dp(root);
return Math.max(res[0],res[1]);
}
public int[] dp(TreeNode root){
int res[]=new int[2];
if(root==null) return res;
int[]left = dp(root.left);
int[]right = dp(root.right);
res[0] = Math.max(left[0],left[1])+Math.max(right[0],right[1]);
res[1] = root.val+left[0]+right[0];
return res;
}
}