• 刷题337. House Robber III


    一、题目说明

    题目337. House Robber III,所有的房子连成二叉树状,不能“抢”直连的两个房间,请问最多可以抢到多少。难度是Medium!

    二、我的解答

    惭愧,这个题目思路始终不对。提交了n次也不正确,看了正确的思路:爷爷节点能偷到的最大钱=max(4个孙子偷的钱 + 爷爷的钱,两个儿子能偷的钱)

    class Solution{
    	public:
    		//recursive + memo
    		int rob(TreeNode* root){
    			
    			if(root==NULL){
    				return 0;
    			} 
    			ump.clear();
    			return	dfs(root);	
    		}
    		int dfs(TreeNode*root){
    			if(root==NULL) return 0;
    			if(ump.count(root)>0){
    				return ump[root];
    			}
    			
    			int money = root->val;
    			if(root->left!=NULL){
    				money += dfs(root->left->left) + dfs(root->left->right);
    			}
    			if(root->right!=NULL){
    				money += dfs(root->right->left) + dfs(root->right->right);
    			}
    			int result = max(money,dfs(root->left)+dfs(root->right));
    			ump[root] = result;
    			return result;
    		}
    	private:
    		unordered_map<TreeNode*,int> ump;
    };
    
    Runtime: 16 ms, faster than 81.99% of C++ online submissions for House Robber III.
    Memory Usage: 23.1 MB, less than 55.56% of C++ online submissions for House Robber III.
    

    三、优化措施

    当然还有其他思路,略!

    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    excel合并单元格
    layer单元格合并
    跨域打开页面:Uncaught DOMException: Blocked a frame with origin
    nginx配置ws
    123
    java集合框架初探-迭代器
    java集合框架初探
    123123
    java switch
    java-测试开始map基本操作
  • 原文地址:https://www.cnblogs.com/siweihz/p/12336507.html
Copyright © 2020-2023  润新知