GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Leetcode-Java/leetcode/solution/src/HouseRobberIII.java at master · Tulpen/Leetcode-Java Expand file tree/ Copy pathHouseRobberIII.javaMore file actions 48 lines (42 loc) · 1.31 KB / Copy pathHouseRobberIII.javaFile metadata and controls48 lines (42 loc) · 1.31 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 public class HouseRobberIII { /** * 效率堪忧,耗时1000ms */ public int rob(TreeNode root) { return rob(root, true); } /** * @param rob true表示不定,false表示不选root */ private int rob(TreeNode root, boolean rob) { if (root == null) { return 0; } if (rob) { return Math.max(root.val + rob(root.left, false) + rob(root.right, false), rob(root.left, true) + rob(root.right, true)); } else { return rob(root.left, true) + rob(root.right, true); } } /** * 优化写法如下,耗时1ms * 这里将两种情况都保存下来并返回给上层,避免了多次重复计算 * val[0]表示不rob当前节点,val[1]表示rob当前节点 */ public int rob2(TreeNode root) { int[] val = helper(root); return Math.max(val[0], val[1]); } private int[] helper(TreeNode node) { if (node == null) { return new int[]{0,0}; } int[] left = helper(node.left); int[] right = helper(node.right); int[] value = new int[2]; value[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]); value[1] = node.val + left[0] + right[0]; return value; } } |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |