代码随想录算法训练营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;
    }
}
相关推荐
小宋加油啊2 小时前
机械臂抓取物体 PVN3D算法调研学习
学习·算法·3d
lqqjuly2 小时前
前沿算法深度解析(一)
算法
小欣加油2 小时前
leetcode1926 迷宫中离入口最近的出口
数据结构·c++·算法·leetcode·职场和发展
happymaker06265 小时前
LeetCodeHot100——42.接雨水
算法
阿正的梦工坊6 小时前
【Rust】07-错误处理:Option、Result 与 ? 运算符
开发语言·算法·rust
八解毒剂7 小时前
数据结构-平衡二叉树——对二叉搜索树的优化
数据结构·c++·算法
运行时记录7 小时前
别再手动写提示词了 — SkillOpt 让技能文档自己进化
算法
啦啦啦啦啦zzzz7 小时前
算法总结(二分查找、双指针)
c++·算法
qq_8573058198 小时前
python语法
开发语言·python·算法