Skip to content

Commit 859fa83

Browse files
authored
feat: add swift implementation to lcof2 problem: No.083 (#3468)
1 parent 582af17 commit 859fa83

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

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

+32
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,38 @@ public class Solution {
247247
}
248248
```
249249

250+
#### Swift
251+
252+
```swift
253+
class Solution {
254+
func permute(_ nums: [Int]) -> [[Int]] {
255+
var res = [[Int]]()
256+
var path = [Int]()
257+
var used = [Bool](repeating: false, count: nums.count)
258+
dfs(0, nums.count, nums, &used, &path, &res)
259+
return res
260+
}
261+
262+
private func dfs(
263+
_ u: Int, _ n: Int, _ nums: [Int], _ used: inout [Bool], _ path: inout [Int], _ res: inout [[Int]]
264+
) {
265+
if u == n {
266+
res.append(path)
267+
return
268+
}
269+
for i in 0..<n {
270+
if !used[i] {
271+
path.append(nums[i])
272+
used[i] = true
273+
dfs(u + 1, n, nums, &used, &path, &res)
274+
used[i] = false
275+
path.removeLast()
276+
}
277+
}
278+
}
279+
}
280+
```
281+
250282
<!-- tabs:end -->
251283

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

0 commit comments

Comments
 (0)