Skip to content

Commit 456dc20

Browse files
author
Hamid Gasmi
committed
#291 is completed with a recursive + memoization approach
1 parent 0bdf368 commit 456dc20

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

09-problems/lc_91_decode_ways.py

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
2+
class SolutionRecursive:
3+
"""
4+
Intuition:
5+
- Backtracking + memoization
6+
7+
Complexity Analysis:
8+
Time Complexity: O(N)
9+
Space Complexity: O(N)
10+
11+
"""
12+
def num_decodings(self, s: str) -> int:
13+
14+
memo = {}
15+
return self.backtrack(s, 0, memo)
16+
17+
def backtrack(self, s: str, idx: int, memo: dict) -> int:
18+
19+
len_s = len(s)
20+
if idx == len_s:
21+
return 1
22+
23+
elif s[idx] == '0':
24+
return 0
25+
26+
elif idx in memo:
27+
return memo[idx]
28+
29+
decoding_count = self.backtrack(s, idx + 1, memo)
30+
if idx + 1 < len_s and int(s[idx: idx + 2]) < 27:
31+
decoding_count += self.backtrack(s, idx + 2, memo)
32+
33+
memo[idx] = decoding_count
34+
35+
return decoding_count

0 commit comments

Comments
 (0)