337. 打家劫舍 III

image.png
image.png

暴力递归(超时)

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public int rob(TreeNode root) {
  18. if(root == null) return 0;
  19. if(root.left == null && root.right == null) return root.val;
  20. //偷父节点
  21. int val1 = root.val;
  22. if(root.left != null) {
  23. val1 += rob(root.left.left) + rob(root.left.right);
  24. }
  25. if(root.right != null) {
  26. val1 += rob(root.right.left) + rob(root.right.right);
  27. }
  28. //不偷父节点
  29. int val2 = rob(root.left) + rob(root.right);
  30. return Math.max(val1,val2);
  31. }
  32. }

记忆化

  1. class Solution {
  2. Map<TreeNode, Integer> map = new HashMap<>();
  3. public int rob(TreeNode root) {
  4. if(root == null) return 0;
  5. if(root.left == null && root.right == null) return root.val;
  6. if(map.containsKey(root) ) {
  7. return map.get(root);
  8. }
  9. //偷父节点
  10. int val1 = root.val;
  11. if(root.left != null) {
  12. val1 += rob(root.left.left) + rob(root.left.right);
  13. }
  14. if(root.right != null) {
  15. val1 += rob(root.right.left) + rob(root.right.right);
  16. }
  17. //不偷父节点
  18. int val2 = rob(root.left) + rob(root.right);
  19. map.put(root,Math.max(val1,val2) );
  20. return Math.max(val1,val2);
  21. }
  22. }

动态规划

  1. class Solution {
  2. public int rob(TreeNode root) {
  3. //dp[0]表示不偷该节点
  4. //dp[1]表示偷该节点
  5. int [] dp = myRob(root);
  6. return Math.max(dp[0],dp[1]);
  7. }
  8. public int [] myRob(TreeNode root ) {
  9. int [] dp = new int [2];
  10. if(null == root ) {
  11. return dp; //初始化为{0,0}
  12. }
  13. int [] left = myRob(root.left);
  14. int [] right = myRob(root.right );
  15. //不偷当前节点,取左右子节点最大值 加和
  16. dp[0] = Math.max(left[0],left[1]) + Math.max(right[0],right[1]) ;
  17. dp[1] = root.val + left[0] + right[0];
  18. return dp;
  19. }
  20. }