File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ func numDecodingsMemoization (s string ) int {
2
+ dp := make ([]int , len (s ) + 1 )
3
+ dp [len (s )] = 1
4
+
5
+ var dfs func (i int ) int
6
+ dfs = func (i int ) int {
7
+ if dp [i ] != 0 {
8
+ return dp [i ]
9
+ } else if s [i ] == '0' {
10
+ return 0
11
+ }
12
+
13
+ res := dfs (i + 1 )
14
+ if i + 1 < len (s ) && (
15
+ s [i ] == '1' || s [i ] == '2' && (s [i + 1 ] >= '0' && s [i + 1 ] <= '6' )) {
16
+ res += dfs (i + 2 )
17
+ }
18
+ dp [i ] = res
19
+ return res
20
+ }
21
+
22
+ return dfs (0 )
23
+ }
24
+
25
+ func numDecodingsTabulation (s string ) int {
26
+ dp := make ([]int , len (s ) + 1 )
27
+ dp [len (s )] = 1
28
+ for i := len (s ) - 1 ; i >= 0 ; i -- {
29
+ if s [i ] == '0' {
30
+ dp [i ] = 0
31
+ } else {
32
+ dp [i ] = dp [i + 1 ]
33
+ }
34
+
35
+ if i + 1 < len (s ) && (
36
+ s [i ] == '1' || s [i ] == '2' && (s [i + 1 ] >= '0' && s [i + 1 ] <= '6' )) {
37
+ dp [i ] += dp [i + 2 ]
38
+ }
39
+ }
40
+ return dp [0 ]
41
+ }
You can’t perform that action at this time.
0 commit comments