代码随想录Day48 | 198.打家劫舍 、213.打家劫舍II 、337.打家劫舍III

198.打家劫舍

dp含义:考虑下标i(包含),能偷得的最大金币数为dp[i]

递推公式:dp[i]=max(dp[i-2]+nums[i],dp[i-1])

初始化:dp[0]=nums[0];dp[1]=max(nums[0],nums[1])

遍历顺序:从小到大

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

213.打家劫舍II 

1.首尾都不考虑

2.考虑首元素,不考虑尾元素(包含情况1)

3.考虑尾元素,不考虑首元素(包含情况1)

class Solution {
public:
    int rob(vector& nums) {
        if (nums.size() == 0) return 0;
        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);
    }
    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];
    }
};

337.打家劫舍III

dp含义:分两种状态dp[0]偷,dp[1]不偷

动规五部曲和递归三部曲相结合的一道题目

/**
 * 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) {
        vectorresult = robTree(root);
        return max(result[0],result[1]);
    }
    vectorrobTree(TreeNode* cur){
        if(cur==NULL)return vector{0,0};
        vectorleft=robTree(cur->left);
        vectorright=robTree(cur->right);
        int val1=cur->val+left[0]+right[0];
        int val2=max(left[0],left[1])+max(right[0],right[1]);
        return {val2,val1};
    }
};

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