代码随想录算法训练营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;
    }
}
相关推荐
NAGNIP12 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队13 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja18 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下18 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶18 小时前
算法 --- 字符串
算法
博笙困了18 小时前
AcWing学习——差分
c++·算法
NAGNIP18 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP18 小时前
大模型微调框架之LLaMA Factory
算法
echoarts18 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客18 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法