From 8f9c8e5fb1f9d89830b92a06f1fc59d97fd84772 Mon Sep 17 00:00:00 2001 From: Luo <82520819+Jerry-306@users.noreply.github.com> Date: Mon, 23 May 2022 10:10:48 +0800 Subject: [PATCH] =?UTF-8?q?1049.=E6=9C=80=E5=90=8E=E4=B8=80=E5=9D=97?= =?UTF-8?q?=E7=9F=B3=E5=A4=B4=E9=87=8D=E9=87=8F=20=E6=96=B0=E5=A2=9Etypesc?= =?UTF-8?q?ript=E7=89=88=E6=9C=AC=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/1049.最后一块石头的重量II.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/problems/1049.最后一块石头的重量II.md b/problems/1049.最后一块石头的重量II.md index ee0ddef2..8d3eeb3b 100644 --- a/problems/1049.最后一块石头的重量II.md +++ b/problems/1049.最后一块石头的重量II.md @@ -277,5 +277,23 @@ var lastStoneWeightII = function (stones) { }; ``` +TypeScript版本 + +```ts +function lastStoneWeightII(stones: number[]): number { + const sum: number = stones.reduce((a: number, b:number): number => a + b); + const target: number = Math.floor(sum / 2); + const n: number = stones.length; + // dp[j]表示容量(总数和)为j的背包所能装下的数(下标[0, i]之间任意取)的总和(<= 容量)的最大值 + const dp: number[] = new Array(target + 1).fill(0); + for (let i: number = 0; i < n; i++ ) { + for (let j: number = target; j >= stones[i]; j--) { + dp[j] = Math.max(dp[j], dp[j - stones[i]] + stones[i]); + } + } + return sum - dp[target] - dp[target]; +}; +``` + -----------------------