337-打家劫舍3

自己的解法

不会。。。

递归(超时)

递归思想(不要深入递归函数体,只需知道递归函数的功能,以及找到跳出递归的边界条件)

思路:
    能盗取的最高金额为 抢劫该节点+抢劫该节点的左孩子的左右子树+抢劫该节点的右孩子的左右子树
    与 抢劫该节点的左子树+抢劫该节点的右子树的和  的最大值
class Solution {
    public int rob(TreeNode root) {
        //递归!
        if(root == null)
            return 0;
        int ans = root.val;
        if(root.left != null) ans += rob(root.left.left) + rob(root.left.right);
        if(root.right != null) ans += rob(root.right.left) + rob(root.right.right);
        return Math.max(ans, rob(root.left) + rob(root.right));
    }
}

动态规划

class Solution {
    public int rob(TreeNode root) {
        //动规!
        //res[0]表示不抢该节点能得到的最大值,res[1]表示抢该节点能得到的最大值
        //res[0](r) = max(res[0](r.left), res[0](r.left)) + max(res[0](r.right), res[0](r.right)) 不抢r时,r的左右孩子可以随便抢(取最大)
        //res[1](r) = r.val + res[0](r.left) + res[0](r.right) 抢r时,r的左右孩子不能被抢
        int[] res = helper(root);
        return Math.max(res[0], res[1]);
    }

    public int[] helper(TreeNode root){
        if(root == null) return new int[2];//默认为0
        int[] l = helper(root.left);
        int[] r = helper(root.right);
        int[] res = new int[2];
        res[0] = Math.max(l[0], l[1]) + Math.max(r[0], r[1]);
        res[1] = root.val + l[0] + r[0];
        return res;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值