Skip to content

Commit 15c991d

Browse files
committed
打家劫舍
1 parent 20437a8 commit 15c991d

File tree

7 files changed

+32
-0
lines changed

7 files changed

+32
-0
lines changed
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

src/dp/rob.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from typing import List
2+
3+
"""
4+
打家劫舍。
5+
"""
6+
class Solution:
7+
def rob(self, nums: List[int]) -> int:
8+
if len(nums) == 0:
9+
return 0
10+
if len(nums) == 1:
11+
return nums[0]
12+
if len(nums) >= 2:
13+
14+
## 初始化dp 以及第一个和第二个结果。
15+
dp = [0] * (len(nums) + 1 )
16+
dp[1] = nums[0]
17+
dp[2] = max(nums[0] , nums[1])
18+
19+
## 从3 开始
20+
for i in range(3 , len(nums) + 1):
21+
if i <= len(nums):
22+
## 接受第i个数字 dp[i -2] + nums[i -1] ,
23+
# 或者是不接受 dp[i -1]
24+
dp[i] = max(dp[i -2] + nums[i -1] , dp[i -1])
25+
26+
print(dp)
27+
return dp[len(nums)]
28+
29+
30+
31+
nums = [1,2,3,1 ,8,1,1]
32+
Solution().rob(nums)
File renamed without changes.

0 commit comments

Comments
 (0)