File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed
lcof2/剑指 Offer II 101. 分割等和子串 Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -156,6 +156,28 @@ func canPartition(nums []int) bool {
156
156
}
157
157
```
158
158
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
+
159
181
<!-- tabs: end -->
160
182
161
183
<!-- solution: end -->
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments