Merge pull request #2693 from markwang1992/1049-lastStoneWeightII

1049.最后一块石头的重量II增加Go二维dp解法
This commit is contained in:
程序员Carl
2024-08-31 17:33:49 +08:00
committed by GitHub

View File

@ -313,6 +313,8 @@ class Solution:
```
### Go
一维dp
```go
func lastStoneWeightII(stones []int) int {
// 15001 = 30 * 1000 /2 +1
@ -341,6 +343,43 @@ func max(a, b int) int {
}
```
二维dp
```go
func lastStoneWeightII(stones []int) int {
sum := 0
for _, val := range stones {
sum += val
}
target := sum / 2
dp := make([][]int, len(stones))
for i := range dp {
dp[i] = make([]int, target + 1)
}
for j := stones[0]; j <= target; j++ {
dp[0][j] = stones[0]
}
for i := 1; i < len(stones); i++ {
for j := 0; j <= target; j++ {
if stones[i] > j {
dp[i][j] = dp[i-1][j]
} else {
dp[i][j] = max(dp[i-1][j], dp[i-1][j-stones[i]] + stones[i])
}
}
}
return (sum - dp[len(stones)-1][target]) - dp[len(stones)-1][target]
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
```
### JavaScript:
```javascript