Palindrome Partitioning III - DP - Recursion w/ Memoization [JS]

Description 

Solution: DP - Recursion w/ Memoization

  1. Populate costs, where costs[i][j] = the minimum cost of turning the substring from index i to j into a palindrome.
  2. Memoize each dp(i, k) : the minimum cost to split substring from index i onwards into k different 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

Comments

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]

Reschedule Meetings for Maximum Free Time I - Sliding Window - Constant Space [JS]