forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SubsetsII.swift
34 lines (27 loc) · 888 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
32
33
34
/**
* 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!), Space Complexity: O(n)
*
*/
class SubsetsII {
func subsetsWithDup(nums: [Int]) -> [[Int]] {
var res = [[Int]]()
var path = [Int]()
let nums = nums.sort({$0 < $1})
_dfs(&res, &path, nums, 0)
return res
}
private func _dfs(inout res: [[Int]], inout _ path:[Int], _ nums: [Int], _ index: Int) {
res.append(Array(path))
for i in index ..< nums.count {
if i > 0 && nums[i] == nums[i - 1] && i != index {
continue
}
path.append(nums[i])
_dfs(&res, &path, nums, i + 1)
path.removeLast()
}
}
}