198. 打家劫舍

  1. if(nums.length==1){
  2. return nums[0];
  3. }
  4. int[]dp=new int[nums.length];
  5. dp[0]=nums[0];
  6. dp[1]=Math.max(nums[0],nums[1]);
  7. for(int i=2;i<dp.length;i++){
  8. dp[i]=Math.max(dp[i-2]+nums[i],dp[i-1]);
  9. }
  10. return dp[dp.length-1];

213. 打家劫舍 II

  1. if(nums.length==1){
  2. return nums[0];
  3. }else if(nums.length==2){
  4. return Math.max(nums[0],nums[1]);
  5. }
  6. int caseone=robcase(nums,0,nums.length-2);
  7. int casetwo=robcase(nums,1,nums.length-1);
  8. return Math.max(caseone,casetwo);
  9. }
  10. private int robcase(int[]nums,int start,int end){
  11. if(end-start==1){
  12. return Math.max(nums[start],nums[end]);
  13. }
  14. int[]dp=new int[nums.length];
  15. dp[start]=nums[start];
  16. dp[start+1]=Math.max(nums[start],nums[start+1]);
  17. for(int i=start+2;i<=end;i++){
  18. dp[i]=Math.max(dp[i-2]+nums[i],dp[i-1]);
  19. }
  20. return dp[end];

337. 打家劫舍 III

  1. int[] robcase = robcase(root);
  2. return Math.max(robcase[0],robcase[1]);
  3. }
  4. private int[] robcase(TreeNode root){
  5. int[]dp=new int[2];
  6. if(root==null){
  7. return dp;
  8. }
  9. int[] left = robcase(root.left);
  10. int[] right = robcase(root.right);
  11. //偷儿子节点
  12. dp[0]=Math.max(left[0],left[1])+Math.max(right[0],right[1]);
  13. dp[1]=left[0]+right[0]+root.val;
  14. return dp;