198. 打家劫舍 - 力扣(LeetCode)
class Solution {
public int rob(int[] nums) {
int[] dp = new int[nums.length];
if(nums.length == 1){
return nums[0];
}
dp[0] = nums[0];
dp[1] = Math.max(nums[0],nums[1]);
for(int i=2;i<nums.length;i++){
dp[i] = Math.max(dp[i-1],dp[i-2]+nums[i]);
}
return dp[nums.length-1];
}
}
213. 打家劫舍 II - 力扣(LeetCode)
class Solution {
public int rob(int[] nums) {
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));
}
public int rob(int[] nums,int beginIndex,int endIndex) {
int[] dp = new int[endIndex-beginIndex+1];
if(dp.length == 1){
return nums[beginIndex];
}
dp[0] = nums[beginIndex];
dp[1] = Math.max(nums[beginIndex],nums[beginIndex+1]);
for(int i=beginIndex+2;i<=endIndex;i++){
dp[i-beginIndex] = Math.max(dp[i-beginIndex-1],dp[i-beginIndex-2]+nums[i]);
}
return dp[dp.length-1];
}
}
337. 打家劫舍 III - 力扣(LeetCode)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int rob(TreeNode root) {
int[] curResult = doRob(root);
return Math.max(curResult[0],curResult[1]);
}
public int[] doRob(TreeNode root){
if(root == null){
return new int[]{0,0};
}
if(root.left == null && root.right == null){
return new int[]{0,root.val};
}
//左子树的值
int[] left = doRob(root.left);
//右子树的值
int[] right = doRob(root.right);
int notSelectCur = Math.max(left[0],left[1]) + Math.max(right[0],right[1]);
int selectCur = root.val + left[0] + right[0];
return new int[]{notSelectCur,selectCur};
}
}