198打家劫舍
class Solution { int dp[]; public int rob(int[] nums) { int len=nums.length; dp=new int[len]; Arrays.fill(dp,-1); return helper(nums,0); } public int helper(int nums[],int start){ if(start>=nums.length){ return 0; } if(dp[start]!=-1) return dp[start]; int res=Math.max(helper(nums,start+1),helper(nums,start+2)+nums[start]); dp[start]=res; return res; } }
- 选择的点就是,对于当前的房子我抢还是不抢,如果抢,我们下一次只能隔着一个房子抢,如果不抢,我们可以抢下一个房子
337. 打家劫舍 III
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { Map<TreeNode,Integer> memo=new HashMap<>(); public int rob(TreeNode root) { if(root==null) return 0; if(memo.containsKey(root)){ return memo.get(root); } //抢 int do_it=root.val+ (root.left==null ? 0 : rob(root.left.left) + rob(root.left.right) )+ (root.right==null ? 0 : rob(root.right.left) + rob(root.right.right) ); //不抢 int not_do=rob(root.left)+rob(root.right); int res=Math.max(do_it,not_do); memo.put(root,res); return res; } }
- 一样的思想,只是数据结构不同,因为树有左右子树,所以会有两个方向