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 7b6deb2

Browse files
feat: add swift solution 2 implementation to lcof2 problem: No.102 (doocs#3615)
1 parent 47b3843 commit 7b6deb2

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

‎lcof2/剑指 Offer II 102. 加减的目标值/README.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,29 @@ func findTargetSumWays(nums []int, target int) int {
241241
}
242242
```
243243

244+
#### Swift
245+
246+
```swift
247+
class Solution {
248+
func findTargetSumWays(_ nums: [Int], _ target: Int) -> Int {
249+
let s = nums.reduce(0, +)
250+
if s - target < 0 || (s - target) % 2 != 0 {
251+
return 0
252+
}
253+
let target = (s - target) / 2
254+
var dp = [Int](repeating: 0, count: target + 1)
255+
dp[0] = 1
256+
257+
for num in nums {
258+
for j in stride(from: target, through: num, by: -1) {
259+
dp[j] += dp[j - num]
260+
}
261+
}
262+
return dp[target]
263+
}
264+
}
265+
```
266+
244267
<!-- tabs:end -->
245268

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

0 commit comments

Comments
(0)

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