Skip to content

Commit 419cf03

Browse files
committed
chore: add daily leetcode post [213]打家劫舍 II_translated
1 parent 817dcce commit 419cf03

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
---
2+
title: 213.Hiccup II
3+
date: '2024.01.01 0:00'
4+
tags:
5+
- Python
6+
- answer
7+
- Array
8+
- Dynamic planning
9+
abbrlink: 85beb0bf
10+
---
11+
# topic:
12+
13+
14+
[topic链接](https://leetcode-cn.com/problems/house-robber-ii/)
15+
16+
# Thought:
17+
这一次终于懂一点Dynamic planning了,The first is the youngest problem,I first thought it was to consider where to start,Start from the first or the second one(这刚好是和Hiccup1Difference)。
18+
但实际上最小子问题还是和Hiccup1Same:Whether to rob the current house。
19+
First we set one`dp`Array,`dp[i]`Indicate robbery to the first`i`The maximum return when a house。
20+
Then we rob the current house after we rob the current house `dp[i] = dp[i-2] + nums[i]`,(Because the house can not be robbed before the current house is robbed),Do not rob the current house `dp[i] = dp[i-1]`
21+
So we can get the state transfer equation:`dp[i] = max(dp[i-2] + nums[i], dp[i-1])`
22+
Last classification discussion and robbery, the first or the second start。
23+
24+
# Code:
25+
26+
```python
27+
class Solution:
28+
def rob(self, nums: List[int]) -> int:
29+
def rob1(nums: List[int]) -> int:
30+
if len(nums) == 1:
31+
return nums[0]
32+
ans = 0
33+
dp = [0] * len(nums)
34+
# def: dp[i]Express the robberyiHome
35+
# theft FirstiHouse,The income isdp[i-2]+nums[i], 不theftFirstiHouse,The income isdp[i-1]
36+
for i in range(len(nums)):
37+
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])
38+
ans = max(ans, dp[i])
39+
return ans
40+
# 打劫First一家,或者First二家开始
41+
return max(rob1(nums[:-1]), rob1(nums[1:])) if len(nums) != 1 else nums[0]
42+
```

0 commit comments

Comments
 (0)