Palindrome-Partitioning: Added memoization

This commit is contained in:
2025-09-15 11:25:53 -04:00
parent d1dead52e1
commit 4ddf200373

View File

@@ -14,20 +14,31 @@ def is_palindrome(s: str) -> bool:
def palindrome_partitions(s: str) -> int:
memo: dict[str, int] = {}
def recurse(s: str) -> int:
nonlocal memo
if len(s) == 0:
return 1
sum = 0
for i in range(1, len(s) + 1):
left = s[:i]
right = s[i:]
left: str = s[:i]
right: str = s[i:]
if is_palindrome(left):
sum += palindrome_partitions(right)
if right not in memo:
memo[right] = palindrome_partitions(right)
sum += memo[right]
return sum
return recurse(s)
# All modules for CS 412 must include a main method that allows it
# to imported and invoked from other python scripts