C++ DP Top-Down


  • 0
    A

    Interesting to see people do this without DP. Here is a top down approach.

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
     
    typedef std::unordered_map<TreeNode*, int> Table;
    class Solution {
    public:
        int rob(TreeNode* root) {
            Table hashtable;
            return brute(root, 0, hashtable);
        }
        
        int brute(TreeNode* root, int sum, Table& hashtable) {
            
             if (root == NULL) {
                    return 0;
             }
             
             Table::iterator val = hashtable.find(root);
             if (val != hashtable.end()) {
                 return val->second;
             }
             
    
             int doskip = (brute(root->left, sum, hashtable) + brute(root->right, sum, hashtable));
             
             int dontskip = root->val;
             if (root->left) {
                     dontskip += brute(root->left->right, sum, hashtable) + brute(root->left->left, sum, hashtable);
             }
             if (root->right) {
                     dontskip += brute(root->right->left, sum, hashtable) + brute(root->right->right, sum, hashtable);
             }
             
             int finalV = std::max(dontskip, doskip);
             hashtable.insert({root, finalV});
             
             return finalV;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.