Skip to content

Commit adf71ed

Browse files
authored
feat: add swift implementation to lcof2 problem: No.084 (#3469)
1 parent 859fa83 commit adf71ed

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

lcof2/剑指 Offer II 084. 含有重复元素集合的全排列/README.md

+34
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,40 @@ public class Solution {
222222
}
223223
```
224224

225+
#### Swift
226+
227+
```swift
228+
class Solution {
229+
func permuteUnique(_ nums: [Int]) -> [[Int]] {
230+
var res = [[Int]]()
231+
var path = [Int]()
232+
var used = [Bool](repeating: false, count: nums.count)
233+
let sortedNums = nums.sorted()
234+
dfs(0, sortedNums.count, sortedNums, &used, &path, &res)
235+
return res
236+
}
237+
238+
private func dfs(
239+
_ u: Int, _ n: Int, _ nums: [Int], _ used: inout [Bool], _ path: inout [Int], _ res: inout [[Int]]
240+
) {
241+
if u == n {
242+
res.append(path)
243+
return
244+
}
245+
for i in 0..<n {
246+
if used[i] || (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
247+
continue
248+
}
249+
path.append(nums[i])
250+
used[i] = true
251+
dfs(u + 1, n, nums, &used, &path, &res)
252+
used[i] = false
253+
path.removeLast()
254+
}
255+
}
256+
}
257+
```
258+
225259
<!-- tabs:end -->
226260

227261
<!-- solution:end -->
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
class Solution {
2+
func permuteUnique(_ nums: [Int]) -> [[Int]] {
3+
var res = [[Int]]()
4+
var path = [Int]()
5+
var used = [Bool](repeating: false, count: nums.count)
6+
let sortedNums = nums.sorted()
7+
dfs(0, sortedNums.count, sortedNums, &used, &path, &res)
8+
return res
9+
}
10+
11+
private func dfs(
12+
_ u: Int, _ n: Int, _ nums: [Int], _ used: inout [Bool], _ path: inout [Int], _ res: inout [[Int]]
13+
) {
14+
if u == n {
15+
res.append(path)
16+
return
17+
}
18+
for i in 0..<n {
19+
if used[i] || (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) {
20+
continue
21+
}
22+
path.append(nums[i])
23+
used[i] = true
24+
dfs(u + 1, n, nums, &used, &path, &res)
25+
used[i] = false
26+
path.removeLast()
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)