leetcode笔记:House Robber III

一. 题目描述

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the “root.” Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that “all houses in this place forms a binary tree”. It will automatically contact the police if two directly-linked houses were broken into on the same night.

Determine the maximum amount of money the thief can rob tonight without alerting the police.

Example 1:

     3
    /    2   3
    \   \
     3   1

Maximum amount of money the thief can rob = 3 + 3 + 1 = 7.

Example 2:

     3
    /    4   5
  / \   \
 1   3   1

Maximum amount of money the thief can rob = 4 + 5 = 9.

二. 题目分析

该题是House Robber II和House Robber的后续。

题目的意思是,小偷找到了一个新的偷盗场所。这片区域只有一个入口,叫做“根”。除了根以外,每个屋子有且仅有一个父屋子。在踩点之后盗贼发现,所有的房间构造形成了一棵二叉树。如果两个直接相连的屋子在同时被盗窃,就会惊动警察。

编写函数判断盗贼在不惊动警察的情况下最多可以偷到的金钱数目。测试用例如题目描述。

针对该题,可使用深度优先搜索来解决。对于当前节点,只有盗窃和不盗窃两种操作,这取决于当前节点的子节点的状态,可用两个变量表示:precurr

pre:当前节点(屋子)不偷盗时,所能获得的收益;取决于在该节点的两个子节点被偷盗时的收益之和

curr:当前节点(屋子)偷盗时,所能获得的收益;由于相邻节点不能同时偷盗否则会引来警察,所以两个子节点不能偷盗,此时收益等于:父节点->val + 左子节点->pre + 右子节点->pre。

比较两种收益pre和curr,取较大者作为当前节点的最大收益。

三. 示例代码

/**
 * 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 Money {
        int pre;  // 该节点不偷,收益为子节点偷的情况下的收益和
        int curr; // 该节点处偷,加上两子节点不偷时的收益
        Money():pre(0), curr(0){}
    };

    int rob(TreeNode* root) {
        Money sum = dfs(root);
        return sum.curr;
    }

    Money dfs(TreeNode* root)
    {
        if (root == NULL) return Money();
        Money leftMoney = dfs(root->left);   // 当前节点的左子节点收益情况
        Money rightMoney = dfs(root->right); // 当前节点的右子节点收益情况
        Money sumMoney;
        sumMoney.pre = leftMoney.curr + rightMoney.curr; // 当前节点不偷
        sumMoney.curr = max(sumMoney.pre, root->val + leftMoney.pre + rightMoney.pre);
        return sumMoney;
    }
};

四. 小结

该题属于DFS的经典题目。

时间: 2024-12-13 08:34:41

leetcode笔记:House Robber III的相关文章

[leetcode] 337.House Robber III

The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized that "all hou

【LeetCode】House Robber III(337)

1. Description The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house. After a tour, the smart thief realized tha

LeetCode 337. House Robber III 动态演示

每个节点是个房间,数值代表钱.小偷偷里面的钱,不能偷连续的房间,至少要隔一个.问最多能偷多少钱 TreeNode* cur mp[{cur, true}]表示以cur为根的树,最多能偷的钱 mp[{cur, false}]表示以cur为根的树,不偷cur节点的钱,最多能偷的钱 可以看出有下面的关系 mp[{node, false}] = mp[{node->left,true}] + mp[{node->right,true}] mp[{node, true}] = max(node->

leetcode笔记

leetcode 笔记 Linked List 2. Add Two Numbers You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a

[leetcode笔记] Remove Duplicates from Sorted List II

问题描述: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. For example,Given 1->2->3->3->4->4->5, return 1->2->5.Given 1->1->1->2->3, return 2-&

leetcode笔记:Pascal's Triangle

一. 题目描写叙述 Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return: [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 二. 题目分析 关于帕斯卡三角形的定义,可參考:http://baike.baidu.com/link?url=qk_-urYQnO4v6v3P4BuMtCa0tMNUqJUk

[leetcode笔记] Longest Consecutive Sequence

随机挑选一题试试手气.   问题描述: Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. Your al

LeetCode House Robber III

原题链接在这里:https://leetcode.com/problems/house-robber-iii/ 题目: The thief has found himself a new place for his thievery again. There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent hous

LeetCode 笔记23 Best Time to Buy and Sell Stock III

Best Time to Buy and Sell Stock III Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit. You may complete at most two transactions. 现在A股涨这么好,要是股票都提前知道价格就好了(@[email pro