代码随想录算法训练营day48 198.打家劫舍 213.打家劫舍|| 317.打家劫舍|||

题目链接198.打家劫舍

复制代码
class Solution {
    public int rob(int[] nums) {
        if(nums.length == 0 || nums == null){
            return 0;
        }
        if(nums.length == 1){
            return nums[0];
        }
        int[] dp = new int[nums.length];
        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.打家劫舍||

复制代码
class Solution {
    public int rob(int[] nums) {
        if(nums.length == 0 || nums == null){
            return 0;
        }
        if(nums.length == 1){
            return nums[0];
        }
        int len = nums.length;
        return Math.max(robCiecle(nums, 0, len-1), robCiecle(nums, 1, len));
    }
    public int robCiecle(int[] nums, int start, int end){
        int x = 0, y = 0, z = 0;
        for(int i = start; i < end; i++){
            x = y;
            y = z;
            z = Math.max(y, x + nums[i]);
        }
        return z;
    }
}

题目链接317.打家劫舍|||

复制代码
/**
 * 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[] res = robAction(root);
        return Math.max(res[0], res[1]);
    }
    public int[] robAction(TreeNode root){
        int[] res = new int[2];
        if(root == null){
            return res;
        }
        int[] left = robAction(root.left);
        int[] right = robAction(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;
    }
}
相关推荐
MM_MS1 小时前
Halcon变量控制类型、数据类型转换、字符串格式化、元组操作
开发语言·人工智能·深度学习·算法·目标检测·计算机视觉·视觉检测
独自破碎E2 小时前
【二分法】寻找峰值
算法
mit6.8242 小时前
位运算|拆分贪心
算法
ghie90903 小时前
基于MATLAB的TLBO算法优化实现与改进
开发语言·算法·matlab
恋爱绝缘体13 小时前
2020重学C++重构你的C++知识体系
java·开发语言·c++·算法·junit
wuk9983 小时前
VSC优化算法MATLAB实现
开发语言·算法·matlab
Z1Jxxx3 小时前
加密算法加密算法
开发语言·c++·算法
乌萨奇也要立志学C++3 小时前
【洛谷】递归初阶 三道经典递归算法题(汉诺塔 / 占卜 DIY/FBI 树)详解
数据结构·c++·算法
vyuvyucd4 小时前
C++引用:高效编程的别名利器
算法
鱼跃鹰飞4 小时前
Leetcode1891:割绳子
数据结构·算法