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 48011af

Browse files
Merge pull request youngyangyang04#849 from RyouMon/master
新增 0416.分割等和子集.md Go解法
2 parents 4dfba4c + 0d2d732 commit 48011af

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
@@ -226,6 +226,32 @@ class Solution:
226226
return taraget == dp[taraget]
227227
```
228228
Go:
229+
```go
230+
// 分割等和子集 动态规划
231+
// 时间复杂度O(n^2) 空间复杂度O(n)
232+
func canPartition(nums []int) bool {
233+
sum := 0
234+
for _, num := range nums {
235+
sum += num
236+
}
237+
// 如果 nums 的总和为奇数则不可能平分成两个子集
238+
if sum % 2 == 1 {
239+
return false
240+
}
241+
242+
target := sum / 2
243+
dp := make([]int, target + 1)
244+
245+
for _, num := range nums {
246+
for j := target; j >= num; j-- {
247+
if dp[j] < dp[j - num] + num {
248+
dp[j] = dp[j - num] + num
249+
}
250+
}
251+
}
252+
return dp[target] == target
253+
}
254+
```
229255

230256
```go
231257
func canPartition(nums []int) bool {

0 commit comments

Comments
(0)

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