From 28e3d95aa9b3e7bace52ec57a018302c22a7e9f8 Mon Sep 17 00:00:00 2001 From: Wen Date: Tue, 26 Oct 2021 22:03:21 +0800 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9E=200213.=E6=89=93=E5=AE=B6?= =?UTF-8?q?=E5=8A=AB=E8=88=8DII.md=20Go=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0213.打家劫舍II.md | 34 +++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/problems/0213.打家劫舍II.md b/problems/0213.打家劫舍II.md index 332d3218..4c536f64 100644 --- a/problems/0213.打家劫舍II.md +++ b/problems/0213.打家劫舍II.md @@ -166,7 +166,41 @@ const robRange = (nums, start, end) => { } ``` Go: +```go +// 打家劫舍Ⅱ 动态规划 +// 时间复杂度O(n) 空间复杂度O(n) +func rob(nums []int) int { + if len(nums) == 1 { + return nums[0] + } + if len(nums) == 2 { + return max(nums[0], nums[1]) + } + + result1 := robRange(nums, 0) + result2 := robRange(nums, 1) + return max(result1, result2) +} +// 偷盗指定的范围 +func robRange(nums []int, start int) int { + dp := make([]int, len(nums)) + dp[1] = nums[start] + + for i := 2; i < len(nums); i++ { + dp[i] = max(dp[i - 2] + nums[i - 1 + start], dp[i - 1]) + } + + return dp[len(nums) - 1] +} + +func max(a, b int) int { + if a > b { + return a + } + return b +} +```