Palindrome Partitioning III - DP - Recursion w/ Memoization [JS]
- Get link
- X
- Other Apps
By
Anna An
on
Solution: DP - Recursion w/ Memoization
- Populate costs, where
costs[i][j]= the minimum cost of turning the substring from indexitojinto a palindrome. - Memoize each
dp(i, k): the minimum cost to split substring from indexionwards intokdifferent palindromes.
Time Complexity: O(n^3 + n^2 * k) 89ms
Space Complexity: O(n^2 + nk) 46.5MB
var palindromePartition = function(s, k) {
let n = s.length, costs = Array(n).fill(0).map(() => Array(n));
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
costs[i][j] = getMinCostToPalindrome(i, j);
}
}
let memo = Array(n).fill(0).map(() => Array(k + 1).fill(-1));
return dp(0, k);
function dp(i, k) {
if (i === n || k === 0) return i === n && k === 0 ? 0 : Infinity;
if (memo[i][k] !== -1) return memo[i][k];
let ans = Infinity;
for (let j = i; j < n; j++) {
ans = Math.min(ans, dp(j + 1, k - 1) + costs[i][j]);
}
return memo[i][k] = ans;
}
function getMinCostToPalindrome(start, end) { // minimum cost to change substring from start to end into a palindrome
let cost = 0;
while (start < end) {
if (s[start] !== s[end]) cost++;
start++, end--;
}
return cost;
}
};
javascript
- Get link
- X
- Other Apps
Comments
Post a Comment