House Robber(打家劫舍问题)

一、LeetCode 198. House Robber

Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
             Total amount you can rob = 1 + 3 = 4.
   public int rob(int[] nums) {
        int len = nums.length;
        if(len == 0) return 0;
        if(len == 1) return nums[0];
        if(len == 2) return Math.max(nums[0], nums[1]);

        int[] dp = new int[len];

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

        return dp[len - 1];

    }

二、LeetCode 213. House Robber II

All houses at this place are arranged in a circle. 

Input: [2,3,2]
Output: 3
Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2),
             because they are adjacent houses.
    public int rob(int[] nums) {
        //将环形拆成两个单排:一种是偷[0, n-1);一种是偷[1, n);
        int len = nums.length;
        if(len == 0) return 0;
        if(len == 1) return nums[0];
        if(len == 2) return Math.max(nums[0], nums[1]);

        int[] dp1 = new int[len];
        dp1[0] = nums[0];
        dp1[1] = Math.max(nums[0], nums[1]);

        int[] dp2 = new int[len];
        dp2[0] = 0;
        dp2[1] = nums[1];

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

        return Math.max(dp1[len - 2], dp2[len - 1]);
    }

三、LeetCode 337. House Robber III

House Robber(打家劫舍问题)_第1张图片

   public int rob(TreeNode root) {
        if(root == null) return 0;

        int temp1 = root.val;
        if(root.left != null) {
            temp1 += rob(root.left.left) + rob(root.left.right);
        }
        if(root.right != null) {
            temp1 += rob(root.right.left) + rob(root.right.right);
        }

        int temp2 = rob(root.left) + rob(root.right);
        

        return Math.max(temp1, temp2);
        
    }

House Robber(打家劫舍问题)_第2张图片

你可能感兴趣的:(LeetCode分类刷题,#,LeetCode树)