• leetcode337


    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int Rob(TreeNode root)
            {
                int[] num = dfs(root);
                return Math.Max(num[0], num[1]);
            }
    
            private int[] dfs(TreeNode x)
            {
                if (x == null) return new int[2];
                int[] left = dfs(x.left);
                int[] right = dfs(x.right);
                int[] res = new int[2];
                res[0] = left[1] + right[1] + x.val;
                res[1] = Math.Max(left[0], left[1]) + Math.Max(right[0], right[1]);
                return res;
            }
    }

    https://leetcode.com/problems/house-robber-iii/#/description

    补充一个python的实现:

     1 class Solution:
     2     def dfs(self,root):
     3         if root==None:
     4             return [0,0]#空节点
     5         counter = [0,0]
     6         left = self.dfs(root.left)
     7         right = self.dfs(root.right)
     8 
     9         #取当前节点,则其左右子节点都不能取
    10         counter[0] =  root.val + left[1] + right[1]
    11         
    12         #不取当前节点,则左右子节点是否选取要看子节点选择是否更大
    13         counter[1] = max(left[0],left[1]) + max(right[0],right[1])
    14         return counter
    15 
    16     def rob(self, root: 'TreeNode') -> 'int':
    17         result = self.dfs(root)
    18         #第一位表示取当前节点的累计值,第二位表示不取当前节点的累计值
    19         return max(result[0],result[1])
  • 相关阅读:
    【NOIP2018】游记
    题解 P1441 【砝码称重】
    题解 P3128 【[USACO15DEC]最大流Max Flow】
    题解 P1949 【聪明的打字员_NOI导刊2011提高(10)】
    题解 P1966 【火柴排队】
    题解 P1895 【数字序列】
    topcoder做题
    1149E
    hdu 6589
    hdu 6579
  • 原文地址:https://www.cnblogs.com/asenyang/p/6970247.html
Copyright © 2020-2023  润新知