Skip to content

Commit 85a3936

Browse files
authored
Merge pull request labuladong#487 from Shantom/master
【198/213/337. 打家劫舍】【Python】
2 parents 4591b79 + 8a2f374 commit 85a3936

File tree

1 file changed

+63
-1
lines changed

1 file changed

+63
-1
lines changed

动态规划系列/抢房子.md

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -258,4 +258,66 @@ int[] dp(TreeNode root) {
258258
<img src="../pictures/qrcode.jpg" width=200 >
259259
</p>
260260

261-
======其他语言代码======
261+
======其他语言代码======
262+
[Shantom](https://github.com/Shantom) 提供 198. House Robber I Python3 解法代码:
263+
264+
```Python
265+
class Solution:
266+
def rob(self, nums: List[int]) -> int:
267+
# 当前,上一间,上上间
268+
cur, pre1, pre2 = 0, 0, 0
269+
270+
for num in nums:
271+
# 当前 = max(上上间+(抢当前),上间(放弃当前))
272+
cur = max(pre2 + num, pre1)
273+
pre2 = pre1
274+
pre1 = cur
275+
276+
return cur
277+
```
278+
[Shantom](https://github.com/Shantom) 提供 213. House Robber II Python3 解法代码:
279+
280+
```Python
281+
class Solution:
282+
def rob(self, nums: List[int]) -> int:
283+
# 只有一间时不成环
284+
if len(nums) == 1:
285+
return nums[0]
286+
287+
# 该函数同198题
288+
def subRob(nums: List[int]) -> int:
289+
# 当前,上一间,上上间
290+
cur, pre1, pre2 = 0, 0, 0
291+
for num in nums:
292+
# 当前 = max(上上间+(抢当前),上间(放弃当前))
293+
cur = max(pre2 + num, pre1)
294+
pre2 = pre1
295+
pre1 = cur
296+
return cur
297+
298+
# 不考虑第一间或者不考虑最后一间
299+
return max(subRob(nums[:-1]), subRob(nums[1:]))
300+
```
301+
[Shantom](https://github.com/Shantom) 提供 337. House Robber III Python3 解法代码:
302+
303+
```Python
304+
class Solution:
305+
def rob(self, root: TreeNode) -> int:
306+
# 返回值0项为不抢该节点,1项为抢该节点
307+
def dp(root):
308+
if not root:
309+
return 0, 0
310+
311+
left = dp(root.left)
312+
right = dp(root.right)
313+
314+
# 抢当前,则两个下家不抢
315+
do = root.val + left[0] + right[0]
316+
# 不抢当前,则下家随意
317+
do_not = max(left) + max(right)
318+
319+
return do_not, do
320+
321+
return max(dp(root))
322+
```
323+

0 commit comments

Comments
 (0)