代码随想录算法训练营第四十八天| LeetCode198.打家劫舍 213.打家劫舍II 337.打家劫舍III

198.打家劫舍

题目:力扣

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

213.打家劫舍II

题目:力扣

class Solution {
public:
    int robRange(vector nums,int start,int end){
        if(start == end) return nums[start];
        vector dp(nums.size(),0);
        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-1],dp[i-2] + nums[i]);
        }
        return dp[end];

    } 
    int rob(vector& nums) {
        if(nums.size() == 1) return nums[0];
        int startR = robRange(nums,0,nums.size() - 2); 
        int endR = robRange(nums,1,nums.size() - 1);
        
        return max(startR,endR);
    } 
};

337.打家劫舍III

题目:力扣

class Solution {
public:
    vector robRange(TreeNode * root){
        if(root == nullptr) return {0,0};
        vector left = robRange(root->left);
        vector right = robRange(root->right);
        int res1 = root->val + left[1] +right[1];
        int res2 = max(left[0],left[1]) + max(right[0],right[1]);
        return {res1,res2};
    }
    int rob(TreeNode* root) {
        vector result = robRange(root);
        return max(result[0],result[1]);
    }
};

总结

题型:动态规划,打家劫舍

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