算法训练营第48天|LeetCode 198.打家劫舍 213.打家劫舍Ⅱ 337.打家劫舍Ⅲ

LeetCode 198.打家劫舍

题目链接:

LeetCode 198.打家劫舍

代码:

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

LeetCode 213.打家劫舍Ⅱ

题目链接:

LeetCode 213.打家劫舍Ⅱ

代码:

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

LeetCode 337.打家劫舍Ⅲ

题目链接:

LeetCode 337.打家劫舍Ⅲ

代码:

class Solution {
public:
    int rob(TreeNode* root) {
        vectorresult = robTree(root);
        return max(result[0],result[1]);
    }
    vectorrobTree(TreeNode*cur){
        //0不偷 1偷
        if(cur==nullptr) return {0,0};
        vectorleft = robTree(cur->left);
        vectorright = robTree(cur->right);
        //偷
        int val1 = cur->val + right[0] + left[0];
        //不偷
        int val2 = max(left[0],left[1]) + max(right[0],right[1]);
        return{val2, val1};
    }
};

你可能感兴趣的:(算法,leetcode,职场和发展)