Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 28e3d95

Browse files
committed
新增 0213.打家劫舍II.md Go解法
1 parent 0d2d732 commit 28e3d95

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

problems/0213.打家劫舍II.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,41 @@ const robRange = (nums, start, end) => {
166166
}
167167
```
168168
Go:
169+
```go
170+
// 打家劫舍Ⅱ 动态规划
171+
// 时间复杂度O(n) 空间复杂度O(n)
172+
func rob(nums []int) int {
173+
if len(nums) == 1 {
174+
return nums[0]
175+
}
176+
if len(nums) == 2 {
177+
return max(nums[0], nums[1])
178+
}
179+
180+
result1 := robRange(nums, 0)
181+
result2 := robRange(nums, 1)
182+
return max(result1, result2)
183+
}
184+
185+
// 偷盗指定的范围
186+
func robRange(nums []int, start int) int {
187+
dp := make([]int, len(nums))
188+
dp[1] = nums[start]
189+
190+
for i := 2; i < len(nums); i++ {
191+
dp[i] = max(dp[i - 2] + nums[i - 1 + start], dp[i - 1])
192+
}
193+
194+
return dp[len(nums) - 1]
195+
}
169196

197+
func max(a, b int) int {
198+
if a > b {
199+
return a
200+
}
201+
return b
202+
}
203+
```
170204

171205

172206

0 commit comments

Comments
 (0)