forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CombinationSumII.swift
38 lines (31 loc) · 1.05 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
/**
* 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]](), path = [Int]()
dfs(&res, &path, target, candidates.sorted(), 0)
return res
}
fileprivate func dfs(_ res: inout [[Int]], _ path: inout [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()
}
}
}