代码随想录算法训练营第47天| 198.打家劫舍、213.打家劫舍II、337.打家劫舍III

198.打家劫舍

完成

思路:

本题中,偷与不偷一个房间,与前两个房间的状态是相关的,可以用动态规划解题。

dp[i]代表能从0-i房间偷取的最大金额。

对于每个房间而言,都有偷和不偷两种选择。如果偷这个房间,那么前一个房间就不能偷了,dp[i] = nums[i] + dp[i-2];如果不偷这个房间,dp[i] = dp[i-1]

代码

class Solution {
    public int rob(int[] nums) {
        // dp[i]代表从0-i的房屋,可以偷到多少钱
        int[] dp = new int[nums.length];
        // 初始化
        dp[0] = nums[0];
        if(nums.length==1) return dp[0];
        else dp[1] = Math.max(nums[0], nums[1]);
        // 根据递推公式遍历
        for (int i = 2; i < nums.length; i++) {
            dp[i] = Math.max(dp[i-1], dp[i-2]+nums[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(robAction(nums, 0, len - 2), robAction(nums, 1, len - 1));
    }
    public int robAction(int[] nums, int start, int end) {
        if (end == start) return nums[start];
        int[] dp = new int[nums.length];
        dp[start] = nums[start];
        dp[start + 1] = Math.max(nums[start], nums[start + 1]);
        for (int i = start + 2; i <= end; i++) {
            dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
        }
        return dp[end];
    }
}

198.打家劫舍

完成

思路:

本题属于树形dp,既要遍历整棵树,又要做动态规划。

难点在于dp数组的定义,如何把树上的每个节点都用dp数组表示。

其实在递归的过程中,系统栈会保存每一层递归的参数。本题dp数组含义:下标为0记录不偷该节点所得到的的最大金钱,下标为1记录偷该节点所得到的的最大金钱。dp数组的长度为2

代码

class Solution {
    public int rob(TreeNode root) {
        int[] res = robAction1(root);
        return Math.max(res[0], res[1]);
    }

    int[] robAction1(TreeNode root) {
        // dp数组,dp[0]不偷该节点所得到的的最大金钱 
        // dp[1]偷该节点所得到的的最大金钱
        int res[] = new int[2];
        if (root == null)
            return res;

        int[] left = robAction1(root.left); // 左孩子的dp数组
        int[] right = robAction1(root.right); // 右孩子的dp数组

        // 递推公式
        // 不偷本节点
        res[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
        // 偷本节点,左右孩子都不能偷
        res[1] = root.val + left[0] + right[0];
        return res;
    }
}
  • 9
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值