代码随想录一刷day48

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、力扣198. 打家劫舍
  • 二、力扣213. 打家劫舍 II
  • 三、力扣337.打家劫舍 III


前言

一、力扣198. 打家劫舍

class Solution {
    public int rob(int[] nums) {
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        if(nums.length == 1){
            return dp[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

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(fun(nums, 0, nums.length - 2), fun1(nums, 1, nums.length - 1));
    }
    public int fun(int[] nums, int low, int high){
        int[] dp = new int[nums.length + 1];
        dp[0] = nums[low];
        dp[1] = Math.max(nums[low], nums[low + 1]);
        for(int i = 2; i <= high; i ++) {
            dp[i] = Math.max(dp[i-1], dp[i-2] + nums[i]);
            System.out.println(dp[i]);
        }
        System.out.println(dp[high-low]);
        return dp[high-low];
    }
    public int fun1(int[] nums, int low, int high){
        int[] dp = new int[nums.length + 1];
        dp[0] = nums[low];
        dp[1] = Math.max(nums[low], nums[low + 1]);
        for(int i = 2, j = 3; i <= high-1 && j <= high; i ++, j ++) {
            dp[i] = Math.max(dp[i-1], dp[i-2] + nums[j]);
        }
        return dp[high-low];
    }
}

三、力扣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 = robAction(root);
        return Math.max(dp[0], dp[1]);
    }

    public int[] robAction(TreeNode root){
        int[] dp = new int[2];
        if(root == null){
            return dp;
        }
        int[] left = robAction(root.left);
        int[] right = robAction(root.right);
        dp[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
        dp[1] = root.val +left[0] + right[0];
        return dp;
    }
}

你可能感兴趣的:(算法,leetcode,数据结构,java,动态规划,排序算法)