Skip to content

Commit 71f6e9e

Browse files
committed
198
1 parent fe8cc7e commit 71f6e9e

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

+3
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,9 @@ Success is like pregnancy, Everybody congratulates you but nobody knows how many
108108
|-----|-------| -------- | ---- | ------|------------|-----|
109109
|70|[Climbing Stairs](https://leetcode.com/problems/climbing-stairs/#/solutions)| [Python [Yu]](./dp/70.py) | _O(N)_| _O(1)_ | Easy| |
110110
|53|[Maximum Subarray](https://leetcode.com/problems/maximum-subarray/#/description)| [Python [Yu]](./dp/53.py) | _O(N)_| _O(N)_ | Easy|[公瑾讲解](https://youtu.be/4tfhDdgu76E) |
111+
|198|[House Robber](https://leetcode.com/problems/house-robber/#/description)| [Python [Yu]](./dp/198.py) | _O(N)_| _O(N)_ | Easy|[公瑾讲解](https://youtu.be/QSjPkgyxCaQ) |
112+
113+
111114

112115
## Dynamic Programming Medium
113116
| # | Title | Solution | Time | Space | Difficulty | Note|

dp/198.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
#!/usr/bin/python
2+
# -*- coding: utf-8 -*-
3+
4+
# Author: Yu Zhou
5+
# 198. House Robber
6+
7+
# DP的思路是比对dp[i-2]+nums[i] 和dp[i-1]的值
8+
# 状态:从0到i,不能选择相邻节点得到的最大值
9+
10+
# DP
11+
# 时间/空间 O(N)
12+
13+
class Solution(object):
14+
def rob(self, nums):
15+
"""
16+
:type nums: List[int]
17+
:rtype: int
18+
数学公式
19+
f(0) = nums[0]
20+
f(1) = max(f(0), f(1))
21+
f(2) = max(nums(2)+ f(0), f(1))
22+
f(3) = max(nums(3)+ f(1), f(2))
23+
.
24+
.
25+
f(n) = max(nums(n) + f(n-2), f(n-1))
26+
"""
27+
# Edge
28+
if not nums:
29+
return 0
30+
if len(nums) == 1:
31+
return nums[0]
32+
33+
34+
# Creating dp
35+
dp = [0 for i in xrange(len(nums))]
36+
dp[0] = nums[0]
37+
dp[1] = max(nums[0], nums[1])
38+
39+
# DP
40+
for i in xrange(2, len(nums)):
41+
dp[i] = max(nums[i] + dp[i-2], dp[i-1])
42+
43+
return dp[-1]

0 commit comments

Comments
 (0)