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