leetcode 72.编辑距离(dp)

链接:https://leetcode-cn.com/problems/edit-distance/submissions/

设dp[i][j]表示串s1前i个字符变换成串s2前j个字符所需要的最小操作次数。

首先要初始化dp数组的第一行和第一列  。

dp[ i ][ j ]分为四种状态:

1. s1[ i ] == s2[ j ] 此时不需要做变化,dp[ i ] [ j ] = dp[ i -1 ] [ j -1 ]。

2. s1[ i ] ! = s2[ j ]分为三种情况:

               第一种:删除s1[ i ], 那么dp[ i ][ j ]  = dp [ i -1 ] [ j ] + 1

               第二种:替换s1[ i ],那么dp[ i ] [ j ]  = dp [ i -1 ] [ j -1 ] + 1

               第三种:插入元素,那么dp[ i ] [ j ] = dp[ i ] [ j -1 ] + 1

三种情况的操作取min值为dp[ i ] [ j ] 的新状态

AC代码:

class Solution {
public:
    int minDistance(string word1, string word2) {
        int dp[word1.length()+1][word2.length()+1];
        dp[0][0] = 0;
        for(int i = 1;i<=word2.length();i++){
            dp[0][i] = i;
        }
        for(int i = 1;i<=word1.length();i++){
            dp[i][0] = i;
        }
        for(int i = 1;i<=word1.length();i++){
            for(int j = 1;j<=word2.length();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-1],min(dp[i-1][j],dp[i][j-1]))+1;
                }
            }
        }
        return dp[word1.length()][word2.length()];
    }
};
原文地址:https://www.cnblogs.com/AaronChang/p/12129632.html