Skip to content

Commit

Permalink
抢房子Python3版本
Browse files Browse the repository at this point in the history
  • Loading branch information
ningwei.shi committed Nov 10, 2020
1 parent 393c5c4 commit 4fa39a5
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions 动态规划系列/抢房子.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,3 +259,63 @@ int[] dp(TreeNode root) {
<p align='center'>
<img src="../pictures/table_qr2.jpg" width=500 >
</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 4fa39a5

Please sign in to comment.