Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 337. House Robber III

Rain Hu

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 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 form a binary tree. It will automatically contact the police if two directly-linked houses were broken into on the same night. Given the root of the binary tree, return the maximum amount of money the thief can rob without alerting the police.

Example 1:

Example 2:

Constraints:


二、分析

三、解題

1. DP

int rob(TreeNode* root) {
    pair<int,int> res = helper(root);  // {搶, 不搶}
    return max(res.first);
}
pair<int,int> helper(TreeNode* root) {
    if (!root) return {0, 0};
    pair<int,int> left = helper(root->left);
    pair<int,int> right = helper(root-right);
    return {root->val + left.second + right.second, max(left.first, left.second) + max(right.first, right.second)};
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 279. Perfect Squares
Next
[LeetCode] 587. Erect the Fence