-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathContents.swift
37 lines (31 loc) · 1.01 KB
/
Contents.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import Foundation
/**
39. Combination Sum
Tags: Array、Backtracking
https://leetcode.com/problems/combination-sum/description/
*/
// 回溯实现
class Solution {
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
var results: [[Int]] = []
var combo: [Int] = []
_combinationSum(&combo, 0, candidates, target, &results)
return results
}
private func _combinationSum(_ combo: inout [Int], _ index: Int, _ candidates: [Int], _ target: Int, _ results: inout [[Int]]) {
if target < 0 {
return
} else if target == 0 {
results.append(combo)
} else {
for i in index..<candidates.count {
let candidate = candidates[i]
combo.append(candidate)
_combinationSum(&combo, i, candidates, target - candidate, &results)
combo.removeLast()
}
}
}
}
Solution().combinationSum([2,3,6,7], 7)
Solution().combinationSum([2,3,5], 8)