代码随想录算法训练营-day48-198.打家劫舍、213.打家劫舍II、337.打家劫舍 III

198.打家劫舍

  1. 学习文章链接:
  2. 思路:见注释
  3. 代码:
class Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        if (nums.length == 1) return nums[0];
        // 考虑下标i(包括i)以内的房屋,最多可以偷窃的金额为dp[i]。
        int[] dp = new int[nums.length];
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0], nums[1]);
        for (int i = 2; i < nums.length; i++) {
            // 
            dp[i] = Math.max(dp[i - 2] + nums[i], dp[i - 1]);
        }
        return dp[nums.length - 1];
    }
}

213.打家劫舍II

  1. 学习文章链接:
  2. 思路:见代码
  3. 代码:
class Solution {
    public int rob(int[] nums) {
        if (nums.length == 0) return 0;
        if (nums.length == 1) return nums[0];
        int res1 = robRange(nums, 0, nums.length - 2);
        int res2 = robRange(nums, 1, nums.length - 1);
        return Math.max(res1, res2);

    }
    public int robRange(int[] nums, int start, int end) {
        if (start == end) 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];
    }
}

337.打家劫舍 III

  1. 学习文章链接:
  2. 思路:见代码
  3. 代码:
/**
 * 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) {
        int[] result = robTree(root);
        return Math.max(result[0], result[1]);
    }
    int[] robTree(TreeNode root) {
        // res[0] 代表不偷,res[1]代表偷
        int[] res = new int[2];
        if (root == null) return res;

        int[] left = robTree(root.left);
        int[] right = robTree(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;
    }
}

你可能感兴趣的:(代码随想录算法训练营,算法,leetcode,动态规划)