C++ DP solution with detailed explanation


  • 0
    D

    This is a typical DP problem,

    int m = word1.size();
    int n = word2.size();
    

    DP array dp[m + 1][n + 1]
    dp[i][j] means how many operations we need to make word1[0 - i] and word2[0-j] equal.
    Initialization:

    dp[0][j] = 0,1,2,3...n
    dp[i][0] = 0,1,2,3...m
    

    we need to compare the word1[i] and word2[j], and return dp[m][n]

    class Solution {
    public:
        int minDistance(string word1, string word2) {
            int m = word1.size();
            int n = word2.size();
            int dp[m + 1][n + 1] = {};
            for(int i = 1; i <= m; i++){
                dp[i][0] = i;
            }
            for(int j = 1; j <= n; j++){
                dp[0][j] = j;
            }
            for(int i = 1; i <= m; i++){
                for(int j = 1; j <= n; j++){
                    if(word1[i - 1] == word2[j - 1]){
                        dp[i][j] = dp[i - 1][j - 1];
                    } else {
                        dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + 1;
                    }
                }
            }
            return dp[m][n];
        }
    };
    

Log in to reply
 

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