LeetCode 337. 打家劫舍 III

https://leetcode-cn.com/problems/house-robber-iii/

枚举,最元素的位置可能隔两层,所以不是贪心。

 树形dp其实就是同时返回两个结果,免得对同一个节点调用两次,免得对一个节点重复调用,使得后面出现重复。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:


    vector<int> cal(TreeNode* root){//不取,取
        if(root==NULL)
            return {0,0};

        auto left_ret=cal(root->left);
        auto right_ret=cal(root->right);

        int no=max(left_ret[0],left_ret[1])+max(right_ret[0],right_ret[1]);
        int yes=root->val +left_ret[0]+right_ret[0];
        return {no,yes};
     
    }

    int rob(TreeNode* root) {
        if(root==NULL)
            return 0;
        auto ret=cal(root);
        return max(ret[0],ret[1]);
    }
};

 

枚举,和上面对比

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:

    unordered_map<string,int> record;

    int cal(TreeNode* root,int mode){
        if(root==NULL)
            return 0;

        string key=to_string((unsigned long long)root)+"|"+to_string(mode);
        if(record.count(key)!=0)
            return record[key];

        if(mode==1){//可取
            int sum1=root->val;
            sum1+=cal(root->left,0);
            sum1+=cal(root->right,0);

            int sum2=0;
            sum2+=cal(root->left,1);
            sum2+=cal(root->right,1);
            int ans=max(sum1,sum2);
            record[key]=ans;
            return ans;
        }
        else{//不可取
            int sum=0;
            sum+=cal(root->left,1);
            sum+=cal(root->right,1);
            record[key]=sum;
            return sum;
        }
    }

    int rob(TreeNode* root) {
        if(root==NULL)
            return 0;
        return max(cal(root,0),cal(root,1));
    }
};

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值