Day 48| 198.打家劫舍 | 213.打家劫舍II |337.打家劫舍III

● 198.打家劫舍

/**
1.dp[i] : 考虑下标i(包括i)以内的房屋,最多可以偷窃的金额为dp[i]
2.确定递推公式
决定dp[i]的因素是i房间偷还是不偷
 */
class Solution {
    public int rob(int[] nums) {
   if(nums == null || nums.length == 0) return 0;
   if(nums.length == 1) return nums[0];
​
   int[] dp = new int[nums.length];
   dp[0] = nums[0];
   dp[1] = Math.max(dp[0],nums[1]);
   for(int i = 2;i<nums.length;i++){
       dp[i] = Math.max(dp[i-1],dp[i-2] + nums[i]);
   //i就是由前面两个推出来的,也就是推或者是不推
   }
   return dp[nums.length- 1];
    }
}

● 213.打家劫舍II

class Solution {
    public int rob(int[] nums) {
    if(nums == null || nums.length == 0){
        return 0;
    }
    int len = nums.length;
    if(len == 1){
        return nums[0];
    }
    return Math.max(getMax(nums,0,len-1),getMax(nums,1,len)); 
    }
    int  getMax(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;
//定义了三个整数变量x、y和z,分别用于保存上一次抢劫的最大价值、当前房屋的价值和当前抢劫的最大价值。
        }
        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;
 *     }
 * }
 */
class Solution {
    public int rob(TreeNode root) {
    /**
    dp[0] and dp[1]表示不偷和偷
     */
     int[] res= robAction(root);
     return Math.max(res[0],res[1]);
    }
    int[] robAction(TreeNode root){
        int res[] = new int[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;
    } 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值