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 0d2d732

Browse files
committed
新增 0416.分割等和子集.md Go解法
1 parent 08199d5 commit 0d2d732

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

‎problems/0416.分割等和子集.md‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -238,6 +238,32 @@ class Solution:
238238
return taraget == dp[taraget]
239239
```
240240
Go:
241+
```go
242+
// 分割等和子集 动态规划
243+
// 时间复杂度O(n^2) 空间复杂度O(n)
244+
func canPartition(nums []int) bool {
245+
sum := 0
246+
for _, num := range nums {
247+
sum += num
248+
}
249+
// 如果 nums 的总和为奇数则不可能平分成两个子集
250+
if sum % 2 == 1 {
251+
return false
252+
}
253+
254+
target := sum / 2
255+
dp := make([]int, target + 1)
256+
257+
for _, num := range nums {
258+
for j := target; j >= num; j-- {
259+
if dp[j] < dp[j - num] + num {
260+
dp[j] = dp[j - num] + num
261+
}
262+
}
263+
}
264+
return dp[target] == target
265+
}
266+
```
241267

242268

243269
javaScript:

0 commit comments

Comments
(0)

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