Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit de57c31

Browse files
1049.最后一块石头的重量II增加Go二维dp解法
1 parent 1609759 commit de57c31

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

‎problems/1049.最后一块石头的重量II.md‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,8 @@ class Solution:
313313

314314
```
315315
### Go:
316+
317+
一维dp
316318
```go
317319
func lastStoneWeightII(stones []int) int {
318320
// 15001 = 30 * 1000 /2 +1
@@ -341,6 +343,43 @@ func max(a, b int) int {
341343
}
342344
```
343345

346+
二维dp
347+
```go
348+
func lastStoneWeightII(stones []int) int {
349+
sum := 0
350+
for _, val := range stones {
351+
sum += val
352+
}
353+
target := sum / 2
354+
355+
dp := make([][]int, len(stones))
356+
for i := range dp {
357+
dp[i] = make([]int, target + 1)
358+
}
359+
for j := stones[0]; j <= target; j++ {
360+
dp[0][j] = stones[0]
361+
}
362+
363+
for i := 1; i < len(stones); i++ {
364+
for j := 0; j <= target; j++ {
365+
if stones[i] > j {
366+
dp[i][j] = dp[i-1][j]
367+
} else {
368+
dp[i][j] = max(dp[i-1][j], dp[i-1][j-stones[i]] + stones[i])
369+
}
370+
}
371+
}
372+
return (sum - dp[len(stones)-1][target]) - dp[len(stones)-1][target]
373+
}
374+
375+
func max(x, y int) int {
376+
if x > y {
377+
return x
378+
}
379+
return y
380+
}
381+
```
382+
344383
### JavaScript:
345384

346385
```javascript

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /