力扣labuladong——一刷day12
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
- 前言
- 一、力扣198. 打家劫舍
- 二、力扣213. 打家劫舍 II
- 三、力扣337. 打家劫舍 III
前言
一、力扣198. 打家劫舍
class Solution {
public int rob(int[] nums) {
int[] dp = new int[nums.length];
if(nums.length == 1)return nums[0];
if(nums.length == 2){
return Math.max(nums[0],nums[1]);
}
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-2] + nums[i], dp[i-1]);
}
return dp[nums.length-1];
}
}
二、力扣213. 打家劫舍 II
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]);
int a = fun(nums,0,nums.length-2);
int b = fun(nums, 1, nums.length-1);
return Math.max(a,b);
}
public int fun(int[] nums, int low, int high){
int[] dp = new int[nums.length];
dp[low] = nums[low];
dp[low+1] = Math.max(nums[low],nums[low+1]);
for(int i = low+2; i <= high; i ++){
dp[i] = Math.max(dp[i-2]+nums[i], dp[i-1]);
}
return dp[high];
}
}
三、力扣337. 打家劫舍 III
/**
* 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[] dp = fun(root);
return Math.max(dp[0],dp[1]);
}
public int[] fun(TreeNode root){
int[] dp = new int[2];
if(root == null){
return dp;
}
int[] dp1 = fun(root.left);
int[] dp2 = fun(root.right);
dp[0] = Math.max(dp1[0],dp1[1])+ Math.max(dp2[0],dp2[1]);
dp[1] = dp1[0]+dp2[0] + root.val;
return dp;
}
}