训练营四十八天 | 198.打家劫舍 ● 213.打家劫舍II ● 337.打家劫舍III

198.打家劫舍  

不要忘记空数组和数组长度为1的情况单独考虑

和前两个状态有关

代码随想录

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];
        //int[] dp = new int[2];
        dp[0] = nums[0];//和前两个状态有关 所以初始化前两个0和1
        dp[1] = Math.max(nums[0], nums[1]);
        //int res;
        for(int i = 2; i < nums.length; i++) {
            dp[i] = Math.max(dp[i-1], dp[i-2] + nums[i]);//考虑前一个与考虑前两个
            //res = Math.max(dp[1], dp[0] + nums[i]);
            //dp[0] = dp[1];
            //dp[1] = res;
        }
        return dp[nums.length - 1];
        //return res;
    }
}

 213.打家劫舍II  

考虑两种情况

只考虑首或者只考虑尾

代码随想录

class Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0)
            return 0;
        if (nums.length == 1)
            return nums[0];
        int num1 = robNum(nums, 0, nums.length - 1);//只考虑头不考虑尾
        int num2 = robNum(nums, 1, nums.length);//不考虑头只考虑尾
        return Math.max(num1, num2);//两者取最大
    }
    public int robNum(int[] nums, int start, int end) {
        int x = 0, y = 0, z = 0;
        for(int i = start; i < end; i++) {
            z = Math.max(y, x + nums[i]);
            x = y;
            y = z;
        }
        return z;
    }
}

 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[] res = robAction(root);
        return Math.max(res[0], res[1]);//取大值
    }
    public 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;
    }
}

 

你可能感兴趣的:(算法,leetcode,数据结构)