当前位置: 首页 > article >正文

LeetCode337. 打家劫舍III

// 很好的一道题目,既考察递归又考察动归
// 这个版本超时了,原因是暴搜
// 很显然这里使用的是前序,那是不是应该考虑后序?
    public int rob(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return root.val;
        }
        if (root.left != null && root.right != null) {
            return Math.max(rob(root.left) + rob(root.right), root.val + rob(root.left.left) + rob(root.left.right) + rob(root.right.left) + rob(root.right.right));
        }
        if (root.left != null) {
            return Math.max(rob(root.left) + rob(root.right), root.val + rob(root.left.left) + rob(root.left.right));
        }
        return Math.max(rob(root.left) + rob(root.right), root.val + rob(root.right.left) + rob(root.right.right));
    }

上面的代码其实非常的丑陋,就算暴搜也不应该这样写,而是这样

public int rob(TreeNode root) {
        if (root == null)
            return 0;
        int money = root.val;
        if (root.left != null) {
            money += rob(root.left.left) + rob(root.left.right);
        }
        if (root.right != null) {
            money += rob(root.right.left) + rob(root.right.right);
        }
        return Math.max(money, rob(root.left) + rob(root.right));
    }

但这题说到底是树形DP题目,最优解法应该是使用DP,如下

    public int rob(TreeNode root) {
       int[] res = robHelper(root);
       return Math.max(res[0], res[1]); 
    }

    private int[] robHelper(TreeNode root) {
        int[] res = new int[2];
        if (root == null) {
            return res;
        }
        int[] left = robHelper(root.left);
        int[] right = robHelper(root.right);

        // 重点:root不偷,下面的结点一定都是偷吗
        // 分为左右结点,像case1:2偷值为2,不偷为3
        // 如果root不偷,下面的左右都偷反而不一定是最大值
        // root不偷,下面的结点有偷与不偷的权利,根据利益最大化选择偷与不偷
        // 但root偷,下面的结点一定不能偷
        // res[0] = left[1] + right[1];
        res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
        res[1] = root.val + left[0] + right[0];
        return res;
    }

http://www.kler.cn/news/314991.html

相关文章:

  • springbootKPL比赛网上售票系统
  • Maven 项目无法下载某个依赖
  • 论 JAVA 集合框架中 接口与类的关系
  • 注册信息安全专业人员(CISP)和网络安全的联系与区别
  • FLStudio21Mac版flstudio v21.2.1.3430简体中文版下载(含Win/Mac)
  • windows cuda12.1 pytorch gpu环境配置
  • js之遍历方法
  • windows@文件系统链接@快捷方式@快捷键方式和符号链接及其对比
  • 本地提权【笔记总结】
  • 《AI:开启未来的无限可能》
  • 【django】局域网访问django启动的项目
  • MongoDB解说
  • 机器人速度雅可比矩阵(机器人动力学)
  • 自动化立体仓库与堆垛机单元的技术参数
  • 设计模式之结构型模式例题
  • 简单题35-搜索插入位置(Java and Python)20240919
  • 如何使用 C# 解决 Cloudflare Turnstile CAPTCHA 挑战
  • Flyway 基本概念
  • 零停机部署的“秘密武器”:为什么 Kamal Proxy 能成为你架构中的不二之选?
  • 面试金典题2.2
  • HarmonyOS 速记
  • java 面试题总结(基础篇)
  • 中泰免签,准备去泰国旅游了吗?《泰语翻译通》app支持文本翻译和语音识别翻译,解放双手对着说话就能翻译。
  • 矩阵分析 线性空间和线性变换 笔记手稿
  • Electron应用程序打包后运行报错cannot find module ‘@vue/cli-service‘
  • 爬虫学习 | 03 爬虫静态网页的爬取(1)
  • 【C++ Primer Plus习题】17.5
  • Linux C高级day3
  • SpringCloud操作mysql
  • 智能工厂的软件设计 运用符号学方法的语言分类学 之0 回顾