88 */
99
1010 class StrobogrammaticNumberII {
11+ let mirrorDigits = [ 0 : 0 , 1 : 1 , 6 : 9 , 8 : 8 , 9 : 6 ]
12+
1113 func findStrobogrammatic( _ n: Int ) -> [ String ] {
12- var res = [ String] ( )
13-
14- guard n >= 1 else {
15- return res
16- }
14+ var path = Array ( repeating: Character ( " " ) , count: n) , paths = [ String] ( )
1715
18- let left = Array ( " 01689 " ) , right = Array ( " 01986 " )
19- var path = Array ( repeating: Character ( " - " ) , count: n)
16+ dfs ( 0 , n - 1 , & path, & paths)
2017
21- dfs ( & res, left, right, 0 , n - 1 , & path)
22-
23- return res
18+ return paths
2419 }
2520
26- fileprivate func dfs( _ res: inout [ String ] , _ left: [ Character ] , _ right: [ Character ] , _ leftIdx: Int , _ path: inout [ Character ] ) {
27- let rightIdx = path. count - leftIdx - 1
28-
29- if leftIdx > rightIdx {
30- res. append ( String ( path) )
21+ private func dfs( _ left: Int , _ right: Int , _ path: inout [ Character ] , _ paths: inout [ String ] ) {
22+ if left > right {
23+ paths. append ( String ( path) )
3124 return
3225 }
3326
34- for i in 0 ..< left . count {
35- if leftIdx == 0 && leftIdx != rightIdx && left [ i ] == " 0 " {
27+ for (key , value ) in mirrorDigits {
28+ if left == right && ( key == 6 || key == 9 ) {
3629 continue
3730 }
38-
39- if leftIdx == rightIdx && ( left [ i] == " 6 " || left [ i] == " 9 " ) {
31+ if left != right && left == 0 && key == 0 {
4032 continue
4133 }
4234
43- path [ leftIdx ] = left [ i ]
44- path [ rightIdx ] = right [ i ]
35+ path [ left ] = Character ( String ( key ) )
36+ path [ right ] = Character ( String ( value ) )
4537
46- dfs ( & res , left, right , leftIdx + 1 , rightIdx - 1 , & path)
38+ dfs ( left + 1 , right - 1 , & path, & paths )
4739 }
4840 }
49- }
41+ }
0 commit comments