Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 5a897d3

Browse files
🐱(dynamic): 213. 打家劫舍 II
1 parent 8eccfd7 commit 5a897d3

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

‎docs/algorithm/dynamic/README.md‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -662,6 +662,59 @@ class Solution(object):
662662
return dp[-1]
663663
```
664664

665+
## 213. 打家劫舍 II
666+
667+
[原题链接](https://leetcode-cn.com/problems/house-robber-ii/)
668+
669+
### 思路
670+
671+
动态规划。
672+
673+
[打家劫舍](https://leetcode-cn.com/problems/house-robber/) 的升级版,加入了一个限制条件:**第一间屋子和最后一间屋子不能同时被抢**。即,**要么抢第一间,要么抢最后一间**
674+
675+
因此,可以把问题拆分为两个基础版的 [打家劫舍](https://leetcode-cn.com/problems/house-robber/):
676+
677+
1. 去掉第一间,打劫一次
678+
2. 去掉最后一间,打劫一次
679+
3. 取两次打劫能获得的最大值
680+
681+
对于基础版打家劫舍而言,设打劫到第 `i` 家的最大收益为 `dp[i]`,则有:
682+
683+
```
684+
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])
685+
```
686+
687+
```python
688+
class Solution:
689+
def rob(self, nums: List[int]) -> int:
690+
691+
length = len(nums)
692+
if length == 0:
693+
return 0
694+
if length == 1:
695+
return nums[0]
696+
if length == 2:
697+
return max(nums[0], nums[1])
698+
699+
def rob_action(nums):
700+
length = len(nums)
701+
dp = [0 for _ in range(length)]
702+
dp[0] = nums[0]
703+
dp[1] = max(nums[0], nums[1])
704+
for i in range(2, length):
705+
dp[i] = max(dp[i - 2] + nums[i], dp[i - 1])
706+
return dp
707+
708+
# 去掉第一间
709+
nums1 = nums[1:]
710+
dp1 = rob_action(nums1)
711+
# 去掉最后一间
712+
nums2 = nums[:-1]
713+
dp2 = rob_action(nums2)
714+
715+
return max(dp1[-1], dp2[-1])
716+
```
717+
665718

666719
## 279. 完全平方数
667720

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /