classSolution{publicintrob(int[] nums){if(nums ==null|| nums.length ==0)return0;int len = nums.length;if(len ==1)return nums[0];returnMath.max(robAction(nums,0, len -1),robAction(nums,1, len));}introbAction(int[] nums,int start,int end){int x =0, y =0, z =0;for(int i = start; i < end; i++){y = z;z =Math.max(y, x + nums[i]);x = y;}return z;}}
三、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;* }* }*/classSolution{// 1.递归去偷,超时publicintrob(TreeNode root){int[] res =robAction(root);returnMath.max(res[0], res[1]);}int[]robAction(TreeNode root){int res[]=newint[2];if(root ==null)return res;int[] left =robAction(root.left);int[] right =robAction(root.right);res[0]=Math.max(left[0], left[1])+Math.max(right[0], right[1]);res[1]= root.val + left[0]+ right[0];return res;}}