Tensorum
YouTubeಕಲಿಯಲು ಪ್ರಾರಂಭಿಸಿ
LeetCode 337 · Tree DP

House Robber III

LeetCode 337 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್‌ಥ್ರೂ

State (node, can_rob); robbing forbids the children.

ಮಧ್ಯಮDynamic ProgrammingTreeDepth-First SearchBinary TreeDP on Trees
LeetCode ನಲ್ಲಿ ತೆರೆಯಿರಿ ↗

ನಾನು House Robber III (LeetCode 337) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Tree DP ಪ್ಯಾಟರ್ನ್‌ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.

ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್‌ನಲ್ಲಿದೆ.

Intuition

Same rob/skip choice as House Robber, but on a tree: if you rob a node you can't rob its children; if you skip it, each child is free to be robbed or not. Memoise on (node, can_rob).

Approach

  1. 1

    dfs(node, can_rob): None → 0.

  2. 2

    can_rob: max(node + children not robbed, children free).

  3. 3

    can't rob: both children free.

  4. 4

    Answer = max of both states at the root.

ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ

Tree DP with memoPythonO(n) time · O(n) space
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def rob(self, root: Optional[TreeNode]) -> int:
        memo={}
        def dfs(node,can_rob):
            key = (id(node),can_rob)
            if node==None:
                return 0
            if key in memo:
                return memo[key]
            if can_rob:
                rob = node.val+dfs(node.left,False)+dfs(node.right,False)
                dontrob=dfs(node.left,True)+dfs(node.right,True)
                memo[key]= max(rob,dontrob)
                return memo[key]
            else:
                memo[key]=dfs(node.left,True)+dfs(node.right,True)
                return memo[key]
        return max(dfs(root,True),dfs(root,False))
ಸ್ಟೆಪ್-ಥ್ರೂ ಲೋಡ್ ಆಗುತ್ತಿದೆ…

House Robber III — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು

House Robber III ಹಿಂದಿನ intuition ಏನು?

Same rob/skip choice as House Robber, but on a tree: if you rob a node you can't rob its children; if you skip it, each child is free to be robbed or not. Memoise on (node, can_rob).

House Robber III (LeetCode 337) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?

1. dfs(node, can_rob): None → 0. 2. can_rob: max(node + children not robbed, children free). 3. can't rob: both children free. 4. Answer = max of both states at the root.

House Robber III ನ time ಮತ್ತು space complexity ಎಷ್ಟು?

Time: O(n). Space: O(n). (Accepted approach: Tree DP with memo.)

House Robber III ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?

Returning a (rob, skip) pair per node avoids the memo dictionary entirely.