Skip to content

Commit 7278ebd

Browse files
committed
213 四状态dp实现
1 parent c6919b0 commit 7278ebd

1 file changed

Lines changed: 35 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
DP思路 缓存依然是两个状态 首家偷不偷 本家偷不偷
3+
cache = [首不偷本不偷, 首不偷本偷, 首偷本不偷, 首偷本偷]
4+
在初始状态和最后结果状态容易下标判断错误
5+
"""
6+
7+
8+
class Solution:
9+
def rob(self, nums) -> int:
10+
if not nums:
11+
return 0
12+
if len(nums) == 1:
13+
return nums[0]
14+
if len(nums) == 2:
15+
return max(nums)
16+
17+
# 初始状态从下标2开始比较容易实现
18+
cache = [0, nums[1], nums[0], nums[0]]
19+
for i in range(2, len(nums) - 1):
20+
v = nums[i]
21+
cache = [
22+
max(cache[0], cache[1]),
23+
v + cache[0],
24+
max(cache[2], cache[3]),
25+
v + cache[2],
26+
]
27+
28+
last = nums[len(nums) - 1]
29+
return max(last + cache[0], cache[1], cache[2], cache[3])
30+
31+
32+
s = Solution()
33+
print(s.rob([2, 3, 2]) == 3)
34+
print(s.rob([1, 2, 3, 2]) == 4)
35+
print(s.rob([1, 2, 3, 1]) == 4)

0 commit comments

Comments
 (0)