Skip to content

Commit 9358daa

Browse files
authored
Create 91-Decode-ways.py
1 parent d5312e7 commit 9358daa

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

91-Decode-ways.py

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution:
2+
def numDecodings(self, s: str) -> int:
3+
# Memoization
4+
dp = { len(s) : 1 }
5+
def dfs(i):
6+
if i in dp:
7+
return dp[i]
8+
if s[i] == "0":
9+
return 0
10+
11+
res = dfs(i + 1)
12+
if (i + 1 < len(s) and (s[i] == "1" or
13+
s[i] == "2" and s[i + 1] in "0123456")):
14+
res += dfs(i + 2)
15+
dp[i] = res
16+
return res
17+
return dfs(0)
18+
19+
# Dynamic Programming
20+
dp = { len(s) : 1 }
21+
for i in range(len(s) - 1, -1, -1):
22+
if s[i] == "0":
23+
dp[i] = 0
24+
else:
25+
dp[i] = dp[i + 1]
26+
27+
if (i + 1 < len(s) and (s[i] == "1" or
28+
s[i] == "2" and s[i + 1] in "0123456")):
29+
dp[i] += dp[i + 2]
30+
return dp[0]

0 commit comments

Comments
 (0)