File tree 2 files changed +69
-0
lines changed
2 files changed +69
-0
lines changed Original file line number Diff line number Diff line change @@ -283,6 +283,43 @@ public class Solution {
283
283
}
284
284
```
285
285
286
+ #### Swift
287
+
288
+ ``` swift
289
+ class Solution {
290
+ private var ans: [String ] = []
291
+ private var cs: [Character ] = []
292
+
293
+ func permutation (_ s : String ) -> [String ] {
294
+ cs = Array (s)
295
+ dfs (0 )
296
+ return ans
297
+ }
298
+
299
+ private func dfs (_ i : Int ) {
300
+ if i == cs.count - 1 {
301
+ ans.append (String (cs))
302
+ return
303
+ }
304
+ var vis: Set <Character > = []
305
+ for j in i..< cs.count {
306
+ if ! vis.contains (cs[j]) {
307
+ vis.insert (cs[j])
308
+ swap (i, j)
309
+ dfs (i + 1 )
310
+ swap (i, j)
311
+ }
312
+ }
313
+ }
314
+
315
+ private func swap (_ i : Int , _ j : Int ) {
316
+ let t = cs[i]
317
+ cs[i] = cs[j]
318
+ cs[j] = t
319
+ }
320
+ }
321
+ ```
322
+
286
323
<!-- tabs: end -->
287
324
288
325
<!-- solution: end -->
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ private var ans : [ String ] = [ ]
3
+ private var cs : [ Character ] = [ ]
4
+
5
+ func permutation( _ s: String ) -> [ String ] {
6
+ cs = Array ( s)
7
+ dfs ( 0 )
8
+ return ans
9
+ }
10
+
11
+ private func dfs( _ i: Int ) {
12
+ if i == cs. count - 1 {
13
+ ans. append ( String ( cs) )
14
+ return
15
+ }
16
+ var vis : Set < Character > = [ ]
17
+ for j in i..< cs. count {
18
+ if !vis. contains ( cs [ j] ) {
19
+ vis. insert ( cs [ j] )
20
+ swap ( i, j)
21
+ dfs ( i + 1 )
22
+ swap ( i, j)
23
+ }
24
+ }
25
+ }
26
+
27
+ private func swap( _ i: Int , _ j: Int ) {
28
+ let t = cs [ i]
29
+ cs [ i] = cs [ j]
30
+ cs [ j] = t
31
+ }
32
+ }
You can’t perform that action at this time.
0 commit comments