forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSubsetsII.swift
31 lines (25 loc) · 839 Bytes
/
SubsetsII.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
/**
* Question Link: https://leetcode.com/problems/subsets-ii/
* Primary idea: Classic Depth-first Search, avoid duplicates by adopting the first occurrence
*
* Time Complexity: O(n * 2^n), Space Complexity: O(n * 2^n)
*
*/
class SubsetsII {
func subsetsWithDup(_ nums: [Int]) -> [[Int]] {
var res = [[Int]](), path = [Int]()
dfs(&res, &path, 0, nums.sorted())
return res
}
private func dfs(_ res: inout [[Int]], _ path: inout [Int], _ idx: Int, _ nums: [Int]) {
res.append(path)
for i in idx..<nums.count {
if i > 0 && nums[i] == nums[i - 1] && i != idx {
continue
}
path.append(nums[i])
dfs(&res, &path, i + 1, nums)
path.removeLast()
}
}
}