leetcode337. House Robbery III/dfs

Topic: 337. House Robbery III

After robbing a street and a circle of houses last time, the thief discovered a new area where theft could be done. There is only one entrance to this area, which we call the "root". In addition to the "root", each house has one and only one "parent" house connected to it. After some reconnaissance, the clever thief realized that "all the houses in this place are arranged like a binary tree." If two directly connected houses are robbed on the same night, the houses will automatically call the police.

Calculate the maximum amount a thief can steal overnight without triggering the alarm.

Example 1:

输入: [3,2,3,null,3,null,1]

     3
    / \
   2   3
    \   \ 
     3   1

输出: 7 
解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1 = 7.

Example 2:

输入: [3,4,5,1,3,null,1]

     3
    / \
   4   5
  / \   \ 
 1   3   1

输出: 9
解释: 小偷一晚能够盗取的最高金额 = 4 + 5 = 9.

Source: LeetCode
Link: https://leetcode-cn.com/problems/house-robber-iii The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Basic idea: dfs

  • There are two options for the current node: steal or not steal
  • Steal: neither of its left or right child nodes can be stolen
  • No stealing: the left and right child nodes can steal or not steal
/**
 * 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:
    map<TreeNode *, vector<int>> m;
    int rob(TreeNode* root) {
    
    
        int res1, res2;
        res1 = fun(root, false);
        res2 = fun(root, true);
        return res1 > res2 ? res1 : res2;
    }
    int fun(TreeNode* root, bool flag){
    
    
        if(root == NULL)
            return 0;
        
        if(m.count(root) && m[root][flag] != INT_MAX)
            return m[root][flag];
        
        m[root] = vector<int>(2, INT_MAX);
        int res1 = 0, res2 = 0;
        int temp = fun(root->left, true) + fun(root->right, true);
        if(flag == true){
    
    //当前节点能偷
            res1 = max(root->val + fun(root->left, false) + fun(root->right, false), temp);
        }
        else{
    
    //当前节点不能偷
            res2 = temp;
        }
        m[root][flag] = res1 > res2 ? res1 : res2;
        return m[root][flag];
    }
};

Guess you like

Origin blog.csdn.net/qq_31672701/article/details/107818798