Palindrome-Partitioning: Added memoization
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
name: Nicholas Tamassia
|
||||
name: Nicholas Tamassia
|
||||
|
||||
Honor Code and Acknowledgments:
|
||||
Honor Code and Acknowledgments:
|
||||
|
||||
This work complies with the JMU Honor Code.
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user