Skip to content

Commit c4e3b56

Browse files
authored
feat: add swift implementation to lcci problem: No.08.07 (doocs#2693)
1 parent 4f2f6a1 commit c4e3b56

File tree

3 files changed

+96
-0
lines changed

3 files changed

+96
-0
lines changed

lcci/08.07.Permutation I/README.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,39 @@ var permutation = function (S) {
208208
};
209209
```
210210

211+
```swift
212+
class Solution {
213+
private var s: [Character] = []
214+
private var vis: [Bool] = Array(repeating: false, count: 128)
215+
private var ans: [String] = []
216+
private var t: String = ""
217+
218+
func permutation(_ S: String) -> [String] {
219+
s = Array(S)
220+
dfs(0)
221+
return ans
222+
}
223+
224+
private func dfs(_ i: Int) {
225+
if i == s.count {
226+
ans.append(t)
227+
return
228+
}
229+
for c in s {
230+
let index = Int(c.asciiValue!)
231+
if vis[index] {
232+
continue
233+
}
234+
vis[index] = true
235+
t.append(c)
236+
dfs(i + 1)
237+
t.removeLast()
238+
vis[index] = false
239+
}
240+
}
241+
}
242+
```
243+
211244
<!-- tabs:end -->
212245

213246
<!-- end -->

lcci/08.07.Permutation I/README_EN.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,39 @@ var permutation = function (S) {
213213
};
214214
```
215215

216+
```swift
217+
class Solution {
218+
private var s: [Character] = []
219+
private var vis: [Bool] = Array(repeating: false, count: 128)
220+
private var ans: [String] = []
221+
private var t: String = ""
222+
223+
func permutation(_ S: String) -> [String] {
224+
s = Array(S)
225+
dfs(0)
226+
return ans
227+
}
228+
229+
private func dfs(_ i: Int) {
230+
if i == s.count {
231+
ans.append(t)
232+
return
233+
}
234+
for c in s {
235+
let index = Int(c.asciiValue!)
236+
if vis[index] {
237+
continue
238+
}
239+
vis[index] = true
240+
t.append(c)
241+
dfs(i + 1)
242+
t.removeLast()
243+
vis[index] = false
244+
}
245+
}
246+
}
247+
```
248+
216249
<!-- tabs:end -->
217250

218251
<!-- end -->
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
private var s: [Character] = []
3+
private var vis: [Bool] = Array(repeating: false, count: 128)
4+
private var ans: [String] = []
5+
private var t: String = ""
6+
7+
func permutation(_ S: String) -> [String] {
8+
s = Array(S)
9+
dfs(0)
10+
return ans
11+
}
12+
13+
private func dfs(_ i: Int) {
14+
if i == s.count {
15+
ans.append(t)
16+
return
17+
}
18+
for c in s {
19+
let index = Int(c.asciiValue!)
20+
if vis[index] {
21+
continue
22+
}
23+
vis[index] = true
24+
t.append(c)
25+
dfs(i + 1)
26+
t.removeLast()
27+
vis[index] = false
28+
}
29+
}
30+
}

0 commit comments

Comments
 (0)