zoukankan      html  css  js  c++  java
  • 337. House Robber III

        /*
         * 337. House Robber III
         * 2016-7-10 by Mingyang
         * I II都是线性的,都用的dp来做,这里我首先想到的也是dp,但是发现在Tree的结构里面表现的不是很合适
         * 后来我想到了前面做过的Largest BST Subtree,那道题目的话返回的是一个array,因为只能返回一样东西
         * 如果要返回两样的话,只能返回一个打包好的array,所以这道题目也是一样,最开始我想的是第一个返回的
         * 是1或者0,0表示我不取我本身,1表示我取我本身,第二个index返回的是这样做的偷的钱数
         * 是大神的思路,每个node都有两个状态,要么偷,要么不偷,第一个index表示如果root被偷了最多的钱
         * 第二个表示如果不被
         * Let's relate rob(root) to rob(root.left) and rob(root.right), etc. 
         * For the 1st element of rob(root), we only need to sum up the larger elements of rob(root.left) and rob(root.right), 
         * respectively, since root is not robbed and we are free to rob the left and right subtrees. 
         * For the 2nd element of rob(root), 
         * however, we only need to add up the 1st elements of rob(root.left) and rob(root.right),
         * respectively, plus the value robbed from "root" itself, 
         * since in this case it's guaranteed that we cannot rob the nodes of root.left and root.right.
         */
        public int rob(TreeNode root) {
            int[] res = robSub(root);
            return Math.max(res[0], res[1]);
        }
        private int[] robSub(TreeNode root) {
            if (root == null) {
                return new int[2];
            }
            int[] left = robSub(root.left);
            int[] right = robSub(root.right);
            int[] res = new int[2];
            res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
            res[1] = root.val + left[0] + right[0];
            return res;
        }
  • 相关阅读:
    Business Objects 基础
    常用的bw基础知识
    SAP BW传输请求操作步骤
    FI/CO 财务基础知识
    SAP财务常用数据源概览
    HANA 和 SAP NetWeaver BW
    Request.QueryString中文乱码
    完全备份类型
    SQL Server备份属于I/O密集型操作
    SQL Server 通过发布订阅 实现数据库同步
  • 原文地址:https://www.cnblogs.com/zmyvszk/p/5659083.html
Copyright © 2011-2022 走看看