mirror of
https://github.com/labuladong/fucking-algorithm.git
synced 2025-07-05 12:04:37 +08:00
Merge pull request #487 from Shantom/master
【198/213/337. 打家劫舍】【Python】
This commit is contained in:
@ -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))
|
||||
```
|
||||
|
||||
|
Reference in New Issue
Block a user