MENU

LeetCode337. 打家劫舍 III

July 14, 2018 • Read: 3297 • LeetCode阅读设置

  • /**
  • * Definition for a binary tree node.
  • * public class TreeNode {
  • * int val;
  • * TreeNode left;
  • * TreeNode right;
  • * TreeNode(int x) { val = x; }
  • * }
  • */
  • class Solution {
  • public Map<TreeNode,Integer> trueCache = new HashMap<TreeNode,Integer>();
  • public Map<TreeNode,Integer> falseCache = new HashMap<TreeNode,Integer>();
  • public int dfs(TreeNode root,boolean canRob) {
  • if(root == null)
  • return 0;
  • if(canRob && trueCache.containsKey(root))
  • return trueCache.get(root);
  • if(!canRob && falseCache.containsKey(root))
  • return falseCache.get(root);
  • int ans = 0;
  • if(canRob)
  • ans = Math.max(ans,
  • root.val + dfs(root.left,false) + dfs(root.right,false));
  • ans = Math.max(ans,
  • dfs(root.left,true) + dfs(root.right,true));
  • if(canRob)
  • trueCache.put(root,ans);
  • if(!canRob)
  • falseCache.put(root,ans);
  • return ans;
  • }
  • public int rob(TreeNode root) {
  • return dfs(root,true);
  • }
  • }
Last Modified: May 12, 2021
Archives Tip
QR Code for this page
Tipping QR Code