方法:dp
具体:dp[i][j]表示:word1[0…i]到word2[0…j]的最小操作数。
如果word1[i]==word2[j],dp[i][j]=dp[i-1][j-1]
否则为三种操作方法得到
dp[i][j]=dp[i][j-1]+1 //i后面插入字符 word2[j]
dp[i][j]=dp[i-1][j]+1 //删除word1[i]
dp[i][j]=dp[i-1][j-1]+1 //替换:word1[i]替换为word2[j]
因此: dp[i][j]=min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) + 1;
边界:word1[0…i]到word2[0…j]的最小操作数 映射为dp[i+1][j+1]
dp[0][0] = 0;
dp[0][1…n] = j;
dp[1…m][0] = i;
class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.size(), n = word2.size();
vector<vector<int>> dp(m + 1, vector<int>(n + 1));
dp[0][0] = 0;
for (int j = 0; j < n; ++j) {
dp[0][j + 1] = j + 1;
}
for (int i = 0; i < m; ++i) {
dp[i + 1][0] = i + 1;
}
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
if (word1[i] == word2[j]) dp[i + 1][j + 1] = dp[i][j];
else dp[i + 1][j + 1] = min(min(dp[i][j + 1], dp[i + 1][j]), dp[i][j]) + 1;
}
}
return dp[m][n];
}
};