leetcode337——打家劫舍III

方法一:

树上dp,通过两个unordered_map记录每个点选择获取或者不选择获取的状态。

选择则状态转移方程为f[o]=o->val+g[o->left]+g[o->right]

不选择点的状态为g[o]=max(f[o->left],g[o->left])+max(f[o->right],g[o->right])

/**
 * 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<TreeNode*,int>f,g;//f代表选择当前结点,o代表不选择当前节点
    void DFS(TreeNode* o)
    {
        if(!o)return;
        DFS(o->left);
        DFS(o->right);
        f[o]=o->val+g[o->left]+g[o->right];
        g[o]=max(f[o->left],g[o->left])+max(f[o->right],g[o->right]);
    }
    int rob(TreeNode* root) {
        DFS(root);
        return max(f[root],g[root]);
    }
};

方法二:

由于父结点的状态只和子节点有关,所以产生可以省去hash表的方法。

/**
 * 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:
    struct SelectItem
    {
        int selected;
        int notSelected;
    };
    SelectItem DFS(TreeNode* o)
    {
        if(!o)return {0,0};
        auto l=DFS(o->left);
        auto r=DFS(o->right);
        int select=o->val+l.notSelected+r.notSelected;
        int notSelect=max(l.selected,l.notSelected)+max(r.selected,r.notSelected);
        return {select,notSelect};
    }
    int rob(TreeNode* root) {
        auto result=DFS(root);
        return max(result.selected,result.notSelected);
    }
};

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值