forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
CombinationSum.swift
35 lines (29 loc) · 957 Bytes
/
CombinationSum.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
/**
* Question Link: https://leetcode.com/problems/combination-sum/
* Primary idea: Classic Depth-first Search
*
* Time Complexity: O(n^n), Space Complexity: O(2^n - 1)
*
*/
class CombinationSum {
func combinationSum(candidates: [Int], _ target: Int) -> [[Int]] {
var res = [[Int]]()
var path = [Int]()
_dfs(candidates.sort({$0 < $1}), target, &res, &path, 0)
return res
}
private func _dfs(candidates: [Int], _ target: Int, inout _ res: [[Int]], inout _ path: [Int], _ index: Int) {
if target == 0 {
res.append(Array(path))
return
}
for i in index ..< candidates.count {
guard candidates[i] <= target else {
break
}
path.append(candidates[i])
_dfs(candidates, target - candidates[i], &res, &path, i)
path.removeLast()
}
}
}