代码随想录算法训练营第四十八天|动态规划part09|● 198.打家劫舍 ● 213.打家劫舍II ● 337.打家劫舍III

●  198.打家劫舍 House Robber - LeetCode

当前是爬一个台阶还是两个台阶

考虑下标i所能偷的最大金币为dp[i]

偷i: dp[i - 2] + nums[i]

不偷i: dp[i - 1]

dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])

class Solution {
    public int rob(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        if (nums.length == 1) return nums[0];
        int n = nums.length;
        int[] dp = new int[n];
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0], nums[1]);

        for (int i = 2; i < n; i++) {
            dp[i] = Math.max(dp[i - 1], dp[i - 2] + nums[i]);
        }

        return dp[n - 1];
    }
}

●  213.打家劫舍II  House Robber II - LeetCode

首尾相连,首尾只能选一个,或者都不选,3种情况

1. 首尾都不选,只考虑中间这段

2. 考虑首元素,不考虑尾元素

3. 不考虑首元素了,只考虑尾元素

2,3包含了1

Max(2, 3)

class Solution {
    public int rob(int[] nums) {
        if (nums.length == 0) return 0;
        if (nums.length == 1) return nums[0];
        int res1 = rob(nums, 0, nums.length - 2);
        int res2 = rob(nums, 1, nums.length - 1);
        return Math.max(res1, res2);
    }

    private int rob(int[] nums, int start, int end) {
        if (end == start) return nums[start];
        int n = nums.length;
        int[] dp = new int[n];
        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.打家劫舍IIIHouse Robber III - LeetCode

记忆化递归

dp[0] 不偷当前节点所获得的最大金额

dp[1] 偷当前节点所获得的最大金钱

后序遍历

最后根节点max(偷,不偷)

        int[] res0 = robTree(root)

        int[] res1 = rotTree(root)

return Max(res0, res1);

int[] robTree(TreeNode root)

        if (root == null) return int[]{0, 0};

        int[] leftdp = robTree(cur.left);

        int[] rightdp = robTree(cur.right);

        int val1 = cur.val + left.dp[0] + right.dp[0];

        int val2 = max(leftdp[0], leftdp[1])+ max( rightdp[0],rightdp[1]);

        return max(val1, val2);

/**
 * 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 {
    /*
    res[0] 不偷
    res[1] 偷
     */
    public int rob(TreeNode root) {
        int[] res = robAction(root);
        return Math.max(res[0], res[1]);
    }

    private 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;
    }
}

        

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