[
dp
palindrome
]
Leetcode 1278. Palindrome Partitioning III
Problem statement
https://leetcode.com/problems/palindrome-partitioning-iii/
Solution
Let us have:
fix(i, j)
be number of steps to make substrings[i:j]
palindrome.dp(i, T)
is answer for from strings[i:]
and forT
parts.
Complexity
Time complexity is O(n^2 * k)
, space is O(n^2)
.
Code
class Solution:
def palindromePartition(self, s, k):
n = len(s)
@lru_cache(None)
def fix(i, j):
if j - i < 1: return 0
return fix(i + 1, j - 1) + (s[i] != s[j])
@lru_cache(None)
def dp(i, T):
if i == n: return abs(T)*n
return min(fix(i, k) + dp(k+1, T-1) for k in range(i, n))
return dp(0, k)