美文网首页
动态规划-树形街区偷窃问题

动态规划-树形街区偷窃问题

作者: mrjunwang | 来源:发表于2018-07-26 15:23 被阅读0次

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.

解题思路:假设树里有N个节点。定义一个函数f(n)为每个节点的最大抢劫量。
第一种情况,不抢父亲:f(root)=f(left)+f(right)//孩子和父亲不能同时抢。
第二种情况:抢父亲:此时需要定义一个新的函数g,表示不抢当前根节点的最大抢劫量,f(root)=root.value+g(root.left)+g(root.right).
g初始化:如果一个节点的左右孩子都为空,则g(n)=0;如果左右孩子有一个为空,且该孩子是叶子节点,则g就等于非空的孩子的节点值。如果左右都不为空,则g(root)=f(left)+f(right)
f初始化:如果节点root的左右孩子均为空,则返回节点root的值。如果左右孩子有一个为空,且该孩子是叶子节点,则返回节点root和左孩子或右孩子中较大的一个的值。

public int getMaxTreeValue(TreeNode<Integer> root) {
        if (root == null) {
            return 0;
        }
        int max1 = root.getValue() + getMaxChildValue(root.getLeft())
                + getMaxChildValue(root.getRight());
        int max2 = getMaxTreeValue(root.getLeft())
                + getMaxTreeValue(root.getRight());
        return Math.max(max1, max2);
    }

    /**
     * @param left
     * @return <p>
     *         Description:
     *         </p>
     */
    public  Integer getMaxChildValue(TreeNode<Integer> root) {
        if (root == null) {
            return 0;
        }
        return getMaxTreeValue(root.getLeft())+getMaxTreeValue(root.getRight());
    }

相关文章

  • 动态规划-树形街区偷窃问题

    The thief has found himself a new place for his thievery ...

  • 树形动态规划

    树形动态规划,顾名思义就是树+DP,先分别回顾一下基本内容吧:动态规划:问题可以分解成若干相互联系的阶段,在每一个...

  • 树形动规

    顾名思义, 树形动态规划就是在“树”的数据结构上的动态规划. 在树上面做动态规划是很常见的, 因为树上的一些问题是...

  • 状压DP——二进制的妙用

    之前我们讲解了背包问题、树形DP,区间DP这三类问题。这些都是中规中矩的动态规划题目。今天,我为大家讲解一种比较有...

  • 动规难题?看看大佬们如何解题。

    上期,我们讲解了树形DP,通过搜索和DP相结合来解决问题。现在,我们将要摆脱搜索的束缚,真正探索动态规划的世界。 ...

  • 打家劫舍问题

    问题一是一个简单的动态规划问题难点是建立合适的状态转移方程dp[i]代表到第i个节点,偷窃的最高金额dp[i-1]...

  • 浅层理解动态规划及利用动态规划解决最长公共子串等问题

    动态规划基本思想 动态规划的工作原理是先解决子问题,再逐步解决大问题。 用动态规划解决旅游规划问题 目前面对的问题...

  • 什么是动态规划

    目录 动态规划解决了什么 什么是动态规划 典型的动态规划 1. 动态规划解决了什么 的思想就是将大问题拆分成小问题...

  • 算法学习收藏

    动态规划问题 动态规划(最优子结构和重叠子问题的比较) 动态规划解决01背包问题 01背包问题 最优二叉查找树 《...

  • 其他来源:数据结构/算法学习笔记

    动态规划问题(Dynamic Programming) 首先,动态规划问题的一般形式就是求最值。动态规划其实是运筹...

网友评论

      本文标题:动态规划-树形街区偷窃问题

      本文链接:https://www.haomeiwen.com/subject/wgbvmftx.html