From 9163ed6b65667e4c95a9ed2b26bd63a6a516fc9f Mon Sep 17 00:00:00 2001 From: zhangzw Date: Wed, 2 Jun 2021 11:49:59 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A01049.=E6=9C=80=E5=90=8E?= =?UTF-8?q?=E4=B8=80=E5=9D=97=E7=9F=B3=E5=A4=B4=E7=9A=84=E9=87=8D=E9=87=8F?= =?UTF-8?q?II=20Go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../1049.最后一块石头的重量II.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/1049.最后一块石头的重量II.md b/problems/1049.最后一块石头的重量II.md index f74600b1..c09e476a 100644 --- a/problems/1049.最后一块石头的重量II.md +++ b/problems/1049.最后一块石头的重量II.md @@ -191,7 +191,33 @@ class Solution: ``` Go: +```go +func lastStoneWeightII(stones []int) int { + // 15001 = 30 * 1000 /2 +1 + dp := make([]int, 15001) + // 求target + sum := 0 + for _, v := range stones { + sum += v + } + target := sum / 2 + // 遍历顺序 + for i := 0; i < len(stones); i++ { + for j := target; j >= stones[i]; j-- { + // 推导公式 + dp[j] = max(dp[j], dp[j-stones[i]]+stones[i]) + } + } + return sum - 2 * dp[target] +} +func max(a, b int) int { + if a > b { + return a + } + return b +} +```