File tree 2 files changed +59
-0
lines changed
2 files changed +59
-0
lines changed Original file line number Diff line number Diff line change @@ -252,6 +252,38 @@ public class Solution {
252
252
}
253
253
```
254
254
255
+ #### Swift
256
+
257
+ ``` swift
258
+ class Solution {
259
+ private var n: Int = 0
260
+ private var s: [Character ] = []
261
+ private var memo: [Int ? ] = []
262
+
263
+ func translateNum (_ num : Int ) -> Int {
264
+ s = Array (String (num))
265
+ n = s.count
266
+ memo = [Int ? ](repeating : nil , count : n)
267
+ return dfs (0 )
268
+ }
269
+
270
+ private func dfs (_ i : Int ) -> Int {
271
+ if i >= n - 1 {
272
+ return 1
273
+ }
274
+ if let cachedResult = memo[i] {
275
+ return cachedResult
276
+ }
277
+ var ans = dfs (i + 1 )
278
+ if s[i] == " 1" || (s[i] == " 2" && s[i + 1 ] < " 6" ) {
279
+ ans += dfs (i + 2 )
280
+ }
281
+ memo[i] = ans
282
+ return ans
283
+ }
284
+ }
285
+ ```
286
+
255
287
<!-- tabs: end -->
256
288
257
289
<!-- solution: end -->
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ private var n : Int = 0
3
+ private var s : [ Character ] = [ ]
4
+ private var memo : [ Int ? ] = [ ]
5
+
6
+ func translateNum( _ num: Int ) -> Int {
7
+ s = Array ( String ( num) )
8
+ n = s. count
9
+ memo = [ Int? ] ( repeating: nil , count: n)
10
+ return dfs ( 0 )
11
+ }
12
+
13
+ private func dfs( _ i: Int ) -> Int {
14
+ if i >= n - 1 {
15
+ return 1
16
+ }
17
+ if let cachedResult = memo [ i] {
18
+ return cachedResult
19
+ }
20
+ var ans = dfs ( i + 1 )
21
+ if s [ i] == " 1 " || ( s [ i] == " 2 " && s [ i + 1 ] < " 6 " ) {
22
+ ans += dfs ( i + 2 )
23
+ }
24
+ memo [ i] = ans
25
+ return ans
26
+ }
27
+ }
You can’t perform that action at this time.
0 commit comments