标签:
/* * 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; }
标签:
原文地址:http://www.cnblogs.com/zmyvszk/p/5659083.html