GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — leetcode-1/algorithms/python/HouseRobberIII/rob.py at master · swangcu/leetcode-1 Expand file tree/ Copy pathrob.pyMore file actions 30 lines (28 loc) · 1.03 KB / Copy pathrob.pyFile metadata and controls30 lines (28 loc) · 1.03 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 """ Answe inspired by the post from here: https://leetcode.com/problems/house-robber-iii/discuss/79330/Step-by-step-tackling-of-the-problem """ # Method 1: dynamic programming solution: def rob1(self, root): lookup = {} def helper(root): if not root: return 0 if root in lookup: return lookup[root] val = 0 if root.left: val += helper(root.left.left) + helper(root.left.right) if root.right: val += helper(root.right.left) + helper(root.right.right) val = max(val + root.val, helper(root.left) + helper(root.right)) lookup[root] = val return val return helper(root) # Method 2: Greedy approach: def rob2(self, root): def helper(root): if not root: return [0, 0] left, right = helper(root.left), helper(root.right) not_robbed = max(left) + max(right) robbed = root.val + left[0] + right[0] return [not_robbed, robbed] return max(helper(root)) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |