LeetCode-337.House Robber III

来源:互联网 发布:软件部门管理制度 编辑:程序博客网 时间:2024/05/23 00:06

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

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all houses in this place forms a binary tree". It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

     3    / \   2   3    \   \      3   1
Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

     3    / \   4   5  / \   \  1   3   1
Maximum amount of money the thief can rob = 4 + 5 = 9.

感觉很简单的一道题,就是没解出来...

/** * 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[] A = dfs(root);        return Math.Max(A[0], A[1]);    }        private int[] dfs(TreeNode node)    {        if (node == null) return new int[2];        int[] left = dfs(node.left);        int[] right = dfs(node.right);        int[] A = new int[2];        A[0] = left[1] + node.val + right[1];        A[1] = Math.Max(left[0], left[1]) + Math.Max(right[0], right[1]);        return A;    }}

解析

A[0]是包括根节点的情况,A[1]是不包含根节点的情况

参考 https://segmentfault.com/a/1190000005029568


0 0
原创粉丝点击