Skip to content

Commit 47b3843

Browse files
authored
feat: add swift implementation to lcof2 problem: No.101 (doocs#3613)
1 parent 8ee2283 commit 47b3843

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

lcof2/剑指 Offer II 101. 分割等和子串/README.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,28 @@ func canPartition(nums []int) bool {
156156
}
157157
```
158158

159+
#### Swift
160+
161+
```swift
162+
class Solution {
163+
func canPartition(_ nums: [Int]) -> Bool {
164+
let s = nums.reduce(0, +)
165+
if s % 2 != 0 { return false }
166+
let target = s / 2
167+
var dp = Array(repeating: false, count: target + 1)
168+
dp[0] = true
169+
170+
for num in nums {
171+
for j in stride(from: target, through: num, by: -1) {
172+
dp[j] = dp[j] || dp[j - num]
173+
}
174+
}
175+
176+
return dp[target]
177+
}
178+
}
179+
```
180+
159181
<!-- tabs:end -->
160182

161183
<!-- solution:end -->
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
class Solution {
2+
func canPartition(_ nums: [Int]) -> Bool {
3+
let s = nums.reduce(0, +)
4+
if s % 2 != 0 { return false }
5+
let target = s / 2
6+
var dp = Array(repeating: false, count: target + 1)
7+
dp[0] = true
8+
9+
for num in nums {
10+
for j in stride(from: target, through: num, by: -1) {
11+
dp[j] = dp[j] || dp[j - num]
12+
}
13+
}
14+
15+
return dp[target]
16+
}
17+
}

0 commit comments

Comments
 (0)