712. Minimum ASCII Delete Sum for Two Strings

Difficulty:
Related Topics:
Similar Questions:

Problem

Given two strings s1 and s2, return **the lowest *ASCII* sum of deleted characters to make two strings equal**.

  Example 1:

Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.

Example 2:

Input: s1 = "delete", s2 = "leet"
Output: 403
Explanation: Deleting "dee" from "delete" to turn the string into "let",
adds 100[d] + 101[e] + 101[e] to the sum.
Deleting "e" from "leet" adds 101[e] to the sum.
At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.
If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.

  Constraints:

Solution

/**
 * @param {string} s1
 * @param {string} s2
 * @return {number}
 */
var minimumDeleteSum = function(s1, s2) {
    var map = {};
    var dfs = function(i, j) {
        var key = i + ',' + j;
        if (map[key]) return map[key];
        if (!s1[i] && !s2[j]) return 0;
        if (!s1[i]) return map[key] = s2.slice(j).split('').reduce((sum, s) => sum + s.charCodeAt(0), 0);
        if (!s2[j]) return map[key] = s1.slice(i).split('').reduce((sum, s) => sum + s.charCodeAt(0), 0);
        if (s1[i] === s2[j]) return map[key] = dfs(i + 1, j + 1);
        return map[key] = Math.min(
            dfs(i + 1, j) + s1.charCodeAt(i),
            dfs(i, j + 1) + s2.charCodeAt(j),
        );
    };
    return dfs(0, 0);
};

Explain:

For every [i, j] in [s1, s2], you could delete a char from s1[i] or s2[j], that end up with two possible ways.

Top down to search and summarize, use map to memorize the result of every path we tried.

We could also go bottom up, that's the reverse version of it, try it yourself!

Complexity: