代码随想录训练营Day48|198.打家劫舍;213.打家劫舍2;337.打家劫舍3

198.打家劫舍

class Solution {
    public int rob(int[] nums) {
        int[] dp= new int[nums.length];
        if(nums.length==1) return nums[0];
        else if(nums.length==2) return Math.max(nums[0],nums[1]);
        dp[0]=nums[0];
        dp[1]=Math.max(nums[0],nums[1]);
        for(int i=2;i

代码随想录训练营Day48|198.打家劫舍;213.打家劫舍2;337.打家劫舍3_第1张图片

 

213.打家劫舍2

class Solution {
    public int rob(int[] nums) {
        int[] dp= new int[nums.length];
        if(nums.length==1) return nums[0];
        else if(nums.length==2) return Math.max(nums[0], nums[1]);
        dp[0] = nums[0];
        dp[1] = Math.max(nums[0], nums[1]);
        for(int i=2;i

代码随想录训练营Day48|198.打家劫舍;213.打家劫舍2;337.打家劫舍3_第2张图片

 

337.打家劫舍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 = backing(root);
        return Math.max(res[0], res[1]);
    }

    private int[] backing(TreeNode cur){
        if(cur==null) return new int[]{0,0};
        int[] left = backing(cur.left);
        int[] right = backing(cur.right);

        int tou = cur.val+left[0]+right[0];
        int butou = Math.max(left[0],left[1]) + Math.max(right[0],right[1]);

        return new int[]{butou, tou};
    }
}

代码随想录训练营Day48|198.打家劫舍;213.打家劫舍2;337.打家劫舍3_第3张图片

 

你可能感兴趣的:(算法,leetcode,动态规划)