Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,38 @@ public class Solution
}
```

#### Swift

```swift
class Solution {
private var ans: [[Int]] = []
private var target: Int = 0
private var candidates: [Int] = []

func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
self.ans = []
self.target = target
self.candidates = candidates
dfs(0, 0, [])
return ans
}

private func dfs(_ sum: Int, _ index: Int, _ current: [Int]) {
if sum == target {
ans.append(current)
return
}
if sum > target {
return
}
for i in index..<candidates.count {
let candidate = candidates[i]
dfs(sum + candidate, i, current + [candidate])
}
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
class Solution {
private var ans: [[Int]] = []
private var target: Int = 0
private var candidates: [Int] = []

func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
self.ans = []
self.target = target
self.candidates = candidates
dfs(0, 0, [])
return ans
}

private func dfs(_ sum: Int, _ index: Int, _ current: [Int]) {
if sum == target {
ans.append(current)
return
}
if sum > target {
return
}
for i in index..<candidates.count {
let candidate = candidates[i]
dfs(sum + candidate, i, current + [candidate])
}
}
}