Skip to content

Commit

Permalink
Merge pull request labuladong#487 from Shantom/master
Browse files Browse the repository at this point in the history
【198/213/337. 打家劫舍】【Python】
  • Loading branch information
labuladong authored Nov 12, 2020
2 parents 4591b79 + 8a2f374 commit 85a3936
Showing 1 changed file with 63 additions and 1 deletion.
64 changes: 63 additions & 1 deletion 动态规划系列/抢房子.md
Original file line number Diff line number Diff line change
Expand Up @@ -258,4 +258,66 @@ int[] dp(TreeNode root) {
<img src="../pictures/qrcode.jpg" width=200 >
</p>

======其他语言代码======
======其他语言代码======
[Shantom](https://github.com/Shantom) 提供 198. House Robber I Python3 解法代码:

```Python
class Solution:
def rob(self, nums: List[int]) -> int:
# 当前,上一间,上上间
cur, pre1, pre2 = 0, 0, 0

for num in nums:
# 当前 = max(上上间+(抢当前),上间(放弃当前))
cur = max(pre2 + num, pre1)
pre2 = pre1
pre1 = cur

return cur
```
[Shantom](https://github.com/Shantom) 提供 213. House Robber II Python3 解法代码:

```Python
class Solution:
def rob(self, nums: List[int]) -> int:
# 只有一间时不成环
if len(nums) == 1:
return nums[0]

# 该函数同198题
def subRob(nums: List[int]) -> int:
# 当前,上一间,上上间
cur, pre1, pre2 = 0, 0, 0
for num in nums:
# 当前 = max(上上间+(抢当前),上间(放弃当前))
cur = max(pre2 + num, pre1)
pre2 = pre1
pre1 = cur
return cur

# 不考虑第一间或者不考虑最后一间
return max(subRob(nums[:-1]), subRob(nums[1:]))
```
[Shantom](https://github.com/Shantom) 提供 337. House Robber III Python3 解法代码:

```Python
class Solution:
def rob(self, root: TreeNode) -> int:
# 返回值0项为不抢该节点,1项为抢该节点
def dp(root):
if not root:
return 0, 0

left = dp(root.left)
right = dp(root.right)

# 抢当前,则两个下家不抢
do = root.val + left[0] + right[0]
# 不抢当前,则下家随意
do_not = max(left) + max(right)

return do_not, do

return max(dp(root))
```

0 comments on commit 85a3936

Please sign in to comment.