712. Minimum ASCII Delete Sum for Two Strings

Given two strings s1, s2, find 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.

Note:

0 < s1.length, s2.length <= 1000.

All elements of each string will have an ASCII value in [97, 122].

最終答案可由許多小的子問題來得到的題型可以用DP來做。dp[i][j]代表的是s1[0...i - 1]和s2[0...j - 1]間最小的delete sum。 dp state transition: dp[i][j] = dp[i - 1][j - 1] if s1[i - 1] == s2[j - 1] dp[i][j] = min(dp[i - 1][j] + s1[i - 1], dp[i][j - 1] + s2[j - 1]) if s1[i - 1] != s2[j - 1]

// Dynamic Programming
int minimumDeleteSum(string s1, string s2) { // time: O(m * n); space: O(m * n)
    int m = s1.length(), n = s2.length();
    vector<vector<int> > dp(m + 1, vector<int> (n + 1, 0));
    // Initialization
    for (int j = 1; j <= n; ++j) 
        dp[0][j] = dp[0][j - 1] + s2[j - 1];
    for (int i = 1; i <= m; ++i) {
        dp[i][0] = dp[i - 1][0] + s1[i - 1];
        for (int j = 1; j <= n; ++j) {
            if (s1[i - 1] == s2[j - 1])
                dp[i][j] = dp[i - 1][j - 1];
            else
                dp[i][j] = min(dp[i - 1][j] + s1[i - 1], dp[i][j - 1] + s2[j - 1]);
        }
    }
    return dp[m][n];
}

仔細觀察可以發現每一個dp grid只跟左邊、上面、左上的grid有關,所以可以只要用1-D dp array搭配幾個變數來完成計算。

// Space Optimized Dynamic Programming
int minimumDeleteSum(string s1, string s2) { // time: O(m * n); space: O(n)
    int m = s1.length(), n = s2.length();
    vector<int> dp(n + 1, 0);
    for (int j = 1; j <= n; ++j)
        dp[j] = dp[j - 1] + s2[j - 1];
    for (int i = 1; i <= m; ++i) {
        int upper_left = dp[0];
        dp[0] += s1[i - 1];
        for (int j = 1; j <= n; ++j) {
            int upper = dp[j];
            dp[j] = s1[i - 1] == s2[j - 1] ? upper_left : min(dp[j - 1] + s2[j - 1], upper + s1[i - 1]);
            upper_left = upper;
        }
    }
    return dp[n];
}

Last updated

Was this helpful?