forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PermutationsII.swift
41 lines (34 loc) · 1.13 KB
/
PermutationsII.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
40
41
/**
* Question Link: https://leetcode.com/problems/permutations-ii/
* Primary idea: Classic Depth-first Search, adopt last occurrence to avoid dupliates
*
* Time Complexity: O(n!), Space Complexity: O(n)
*
*/
class PermutationsII {
func permuteUnique(nums: [Int]) -> [[Int]] {
var res = [[Int]]()
var path = [Int]()
var visited = [Bool](count: nums.count, repeatedValue: false)
let nums = nums.sorted(by: <)
_dfs(&res, &path, nums, &visited)
return res
}
private func _dfs(inout res: [[Int]], inout _ path: [Int], _ nums: [Int], inout _ visited: [Bool]) {
// termination case
if path.count == nums.count {
res.append(Array(path))
return
}
for i in 0..<nums.count {
if visited[i] || (i > 0 && nums[i] == nums[i - 1] && visited[i - 1]) {
continue
}
path.append(nums[i])
visited[i] = true
_dfs(&res, &path, nums, &visited)
visited[i] = false
path.removeLast()
}
}
}