代码随想录第48天|198.打家劫舍, 213.打家劫舍II ,337.打家劫舍III

LeetCode198.打家劫舍

题目链接:198. 打家劫舍 - 力扣(LeetCode)

思路:

class Solution {
public:
    int rob(vector& nums) {
        if(nums.size() == 0) return 0;
        if(nums.size() == 1) return nums[0];
        vector dp(nums.size());//最多偷窃金额
        dp[0] = nums[0];//初始化
        dp[1] = max(nums[0], nums[1]);
        for(int i = 2; i < nums.size(); i++) {
            dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]);//前一个为偷i房间,后一个为不偷i
        }
        return dp[nums.size() - 1];
    }
};

LeetCode213.打家劫舍II

题目链接:213. 打家劫舍 II - 力扣(LeetCode)

思路:

class Solution {
public:
    int rob(vector& nums) {
        if(nums.size() == 0) return 0;
        if(nums.size() == 1) return nums[0];
        int result1 = robrange(nums, 1, nums.size() - 1);//不考虑首
        int result2 = robrange(nums, 0, nums.size() - 2);//不考虑尾
        return max(result1, result2);
    }

    int robrange(vector& nums, int start, int end) {
        if(end == start) return nums[start];
        vector dp(nums.size());//首尾相邻偷最多钱
        dp[start] = nums[start];//初始化
        dp[start + 1] = max(nums[start], nums[start + 1]);
        for(int i = start + 2; i <= end; i++) {
            dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]);//递推
        }
        return dp[end];
    }
};

LeetCode 337.打家劫舍III

题目链接:337. 打家劫舍 III - 力扣(LeetCode)

思路:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int rob(TreeNode* root) {
        vector result = robTree(root);
        return max(result[0], result[1]);
    }
    //长度为二的数组,0:不偷,1:偷
    vector robTree(TreeNode* cur) {
        if(cur == NULL) return vector {0, 0};
        vector left =  robTree(cur->left);
        vector right = robTree(cur->right);
        //偷cur不能偷左右节点
        int val1 = cur->val + left[0] + right[0];
        //不偷cur那么可以偷也可以不偷左右节点,比大小看谁大取谁
        int val2 = max(left[0], left[1]) + max(right[0], right[1]);
        return {val2, val1};
    }
};

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