代码随想录算法训练营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;
    }
}
相关推荐
安忘1 小时前
LeetCode-274.H 指数
算法·leetcode·职场和发展
xxxmmc1 小时前
Leetcode 160 Intersection of Two Linked Lists
算法·leetcode·双指针
VincentStory2 小时前
分享一个项目中遇到的一个算法题
android·算法
ylfhpy5 小时前
Java面试黄金宝典1
java·开发语言·算法·面试·职场和发展
这个懒人5 小时前
SB重删算法详解:原理、架构与实现
c++·算法·哈希算法
Cachel wood6 小时前
Mysql相关知识:存储引擎、sql执行流程、索引失效
android·人工智能·sql·mysql·算法·前端框架·ab测试
wen__xvn6 小时前
每日一题洛谷P1106 删数问题c++
开发语言·c++·算法
_GR6 小时前
2020年蓝桥杯第十一届C&C++大学B组(第二次)真题及代码
c语言·数据结构·c++·算法·蓝桥杯
SomeB1oody6 小时前
【Python机器学习】3.2. 决策树理论(进阶):ID3算法、信息熵原理、信息增益
python·算法·决策树·机器学习
维齐洛波奇特利(male)7 小时前
(暴力枚举 水题 长度为3的不同回文子序列)leetcode 1930
算法·leetcode·职场和发展