leetcode 712

The idea of ​​​​this question: I got it based on the idea of ​​the longest common subsequence.

The longest common subsequence is: d[i][j] represents the longest common subsequence of the first i (0~i-1) characters of the string s1 and the first j (0~j-1) characters of the string s2 sequence.

Discuss by situation:

  When s1[i-1] == s2[j-1], d[i][j] = d[i-1][j-1]+1; this means that when the i-1th character When the same, just add one to the length of the previous d[i-1][j-1]

      When s1[i-1] != s2[j-1], the value of d[i][j] may have two cases:

      (1) d[i][j] = d[i-1][j], which means that the longest common subsequence of d[i][j] has no string s1[i-1]. Then it is equivalent to the longest common subsequence of string s1 (0~i-2) and string s2 (0~j-1)

      (2) d[i][j] = d[i][j-1], which means that the longest common subsequence of d[i][j] has no string s2[i-1]. Then it is equivalent to the longest common subsequence of the string s1 (0~i-1) and the string s2 (0~j-2).

       综上,d[i][j] = max(d[i-1][j],d[i][j-1])

According to the above thinking, think about the 712 question. The meaning of this question is to delete characters to make the two strings equal, and add the deleted characters to make the sum of the deleted strings the smallest.

You can set d[i][i] to represent the minimum sum of deleted characters that keep the first i (0~i-1) characters of string s1 equal to the first j (0~j-1) characters of string s2

Then for d[i][j], it is also discussed separately:

      When s1[i-1] ==s2[j-1] , which means that s1[i-1] and s2[j-1] do not need to be deleted, then d[i][j] = d[i-1 ][j-1]      

      When s1[i-1]!=s2[j-1], no two characters are needed, then d[i][j] = d[i-1][j-1]+s1[i-1]+ s2[j-1]      

      For further discussion, regardless of whether s1[i-1] and s2[j-1] are equal,

        (1) Do not s1[i-1], find the minimum sum of deleted strings in s1[0~i-2] and s2[0~j-1]

        (2) Do not s2[j-1], find the minimum sum of deleted strings in s1[0~i-1] and s2[0~j-2]

code show as below:

class Solution {
public:
    int minimumDeleteSum(string s1, string s2) {
        int m = s1.length();
        int n =s2.length();
        int d[m+1][n+1];
        d[0][0] = 0;
        for(int i =1;i<=m;i++)
            d[i][0] = d[i-1][0]+s1[i-1];
        for(int j =1;j<=n;j++)
            d[0][j] = d[0][j-1]+s2[j-1];
        for(int i=1;i<=m;i++)
            for(int j=1;j<=n;j++)
            {
                d[i][j] = min(d[i-1][j]+s1[i-1],d[i][j-1]+s2[j-1]);
                if(s1[i-1]==s2[j-1])
                    d[i][j] = min(d[i][j],d[i-1][j-1]);
                else
                    d[i][j] - min(d[i][j],d[i-1][j-1]+s1[i-1]+s2[j-1]);
            }
        return d[m][n];
    }
};

 

     

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325900793&siteId=291194637