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

目录

  • Leetcode198.打家劫舍
  • Leetcode213.打家劫舍II
  • Leetcode337.打家劫舍 III

Leetcode198.打家劫舍

文章链接:代码随想录
题目链接:198.打家劫舍

思路:偷到当前这家的金额分两种状态,偷当前这家就是上上家加这家,要不不偷就和上家一样,取个最大值。

class Solution {
public:
    int rob(vector<int>& nums) {
        if (nums.size() == 1) return nums[0];
        vector<int> dp(nums.size());
        dp[0] = nums[0];
        dp[1] = max(nums[1], nums[0]);
        for (int i = 2; i < nums.size(); i++){
            dp[i] = max(dp[i - 2] + nums[i], dp[i - 1]);
        }
        return dp[nums.size() - 1];
    }
};

Leetcode213.打家劫舍II

文章链接:代码随想录
题目链接:213.打家劫舍II

思路:掐头去尾,把上一题分两种情况做,取个最大值。

class Solution {
public:
    int robRange(vector<int>& nums, int start, int end){
        if (start == end) return nums[start];
        vector<int> dp(end - start + 1);
        dp[0] = nums[start];
        dp[1] = max(nums[start + 1], nums[start]);
        for (int i = 2; i < dp.size(); i++){
            dp[i] = max(dp[i - 1], dp[i - 2] + nums[i + start]);
        }
        return dp[dp.size() - 1];
    }
    
    int rob(vector<int>& nums) {
        if (nums.size() == 1) return nums[0];
        int result1 = robRange(nums, 0, nums.size() - 2);
        int result2 = robRange(nums, 1, nums.size() - 1);
        return max(result1, result2);
    }
};

Leetcode337.打家劫舍 III

文章链接;代码随想录
题目链接:337.打家劫舍 III

思路:也是分两种状态,当前节点偷或者不偷,记录两个值,反到根节点,取个最大值(后序遍历)。

/**
 * 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:
    vector<int> robTree(TreeNode* cur){
        if (cur == NULL) return vector<int> {0, 0};
        vector<int> left = robTree(cur->left);
        vector<int> right = robTree(cur->right);

        int val1 = cur->val + left[0] + right[0];
        int val2 = max(left[0], left[1]) + max(right[0], right[1]);
        return vector<int> {val2, val1};
    }
    
    int rob(TreeNode* root) {
        vector<int> result = robTree(root);
        return max(result[0], result[1]);
    }
};

第四十七天休息,第四十八天打卡。数据库基本操作学完了,今天开始撸项目,加油!!!

你可能感兴趣的:(算法)