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