712. Minimum ASCII Delete Sum for Two Strings

Posted learning-c

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了712. Minimum ASCII Delete Sum for Two Strings相关的知识,希望对你有一定的参考价值。

动态规划 
空间复杂度O(mn)
第一次提交
class Solution {
public:
    int minimumDeleteSum(string s1, string s2) {
        //cout<<"s1: "<<s1<<endl;
        //cout<<"s2: "<<s2<<endl;
        int m=s1.size();
        int n=s2.size();
        vector<vector<int>> dp(m+1,vector<int>(n+1,0));
        for(int i=0;i<m;i++){
            dp[i+1][0]=dp[i][0]+s1[i];
            for(int j=0;j<n;j++){
                dp[0][j+1]=dp[0][j]+s2[j];
                if(s1[i]==s2[j])
                    dp[i+1][j+1]=dp[i][j];
                else
                    dp[i+1][j+1]=min(dp[i][j+1]+s1[i],dp[i+1][j]+s2[j]);
            }
        }
        /*
        for(int i=0;i<m+1;++i){
            for(int j=0;j<n+1;++j){
                cout<<dp[i][j]<<" ";
            }
            cout<<endl;
        }
        */
        return dp[m][n];
    }
};

 动态规划 空间复杂度 min(O(m),O(n))

 1 class Solution {
 2 public:
 3     int minimumDeleteSum(string s1, string s2) {
 4         //cout<<"s1: "<<s1<<endl;
 5         //cout<<"s2: "<<s2<<endl;
 6         //int m=s1.size();
 7         int m=s1.size();
 8         int n=s2.size();
 9         vector<int> dp(n+1,0);
10         for(int j=0;j<n;++j)
11             dp[j+1]=dp[j]+s2[j];
12         for(int i=0;i<m;++i){
13             int t1=dp[0];
14             dp[0]=dp[0]+s1[i];
15             for(int j=0;j<n;++j){
16                 int t2=dp[j+1];
17                 if(s1[i]==s2[j])
18                     dp[j+1]=t1;
19                 else
20                     dp[j+1]=min(dp[j+1]+s1[i],dp[j]+s2[j]);
21                 t1=t2;
22             }
23         }
24         return dp[n];
25     }
26 };

python 代码

class Solution(object):
    def minimumDeleteSum(self, s1, s2):
        """
        :type s1: str
        :type s2: str
        :rtype: int
        """
        m=len(s1)
        n=len(s2)
        dp=[[0 for _ in xrange(len(s2)+1)] for _ in xrange(len(s1)+1)]
        for j in xrange(1,len(s2)+1):
            dp[0][j]=dp[0][j-1]+ord(s2[j-1])
        for i in xrange(1,len(s1)+1):
            dp[i][0]=dp[i-1][0]+ord(s1[i-1])
            #print "dp[{}][0]: {}".format(i,dp[i][0])
            for j in xrange(1,len(s2)+1):
                if s1[i-1]==s2[j-1]:
                    dp[i][j]=dp[i-1][j-1]
                else:
                    dp[i][j]=min(dp[i-1][j]+ord(s1[i-1]),dp[i][j-1]+ord(s2[j-1]))
                    
                    
        #print dp
        
        return dp[-1][-1]

 

以上是关于712. Minimum ASCII Delete Sum for Two Strings的主要内容,如果未能解决你的问题,请参考以下文章

712. Minimum ASCII Delete Sum for Two Strings

712. Minimum ASCII Delete Sum for Two Strings

712. Minimum ASCII Delete Sum for Two Strings

712. Minimum ASCII Delete Sum for Two Strings

[LeetCode] Minimum ASCII Delete Sum for Two Strings 两个字符串的最小ASCII删除和

Q712 两个字符串的最小ASCII删除和