C++ dp


  • 0
    B

    first find the longest common sequence
    then the solution is the total length minus length of LCS

    class Solution {
    public:
        int minDistance(string word1, string word2) {
            int len1 = word1.length(), len2 = word2.length();
            vector<vector<int>>dp(len1+1, vector<int>(len2+1, 0));
    
            for(int i = 1; i <= len1; i++)
            {
                for(int j = 1; j <= len2; j++)
                {
                    dp[i][j] = max(dp[i-1][j-1], max(dp[i-1][j], dp[i][j-1]));
                    if(word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
                }
            }
            return len1 + len2 - 2*dp[len1][len2];
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.