30 Day Challenge Day 22 | Leetcode 72. Edit Distance
题解
Hard
动态规划
这道题是一道很具有代表性的二维动态规划问题,非常具有示范效应,理解了这道题的思路,能够举一反三。
一开始没有思路的时候,用一个小例子手动演算一下很有帮助。
Example: word1: abc, word2: abbc
\0 a b b c
\0 0 1 2 3 4
a 1 0 1 2 3
b 2 1 0 1 2
c 3 2 1 1 1
DP:
state:
dp[i][j] word1[0-i] --> word2[0-j]
initialization:
1st row: dp[0][j] = j;
1st col: dp[i][0] = i;
transition:
case: word1[i-1] == word2[j-1] ==> dp[i][j] = dp[i-1][j-1]
case: word1[i-1] != word2[j-1] ==> dp[i][j] = min(dp[i][j-1], dp[i-1][j]) + 1 <== missing dp[i-1][j-1]
delete insert replace
result:
dp[m][n]
*****/
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, 0));
// initialization
for(int i = 0; i <= m; i++) {
dp[i][0] = i;
}
for(int j = 0; j <= n; j++) {
dp[0][j] = j;
}
// state transition
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-1], min(dp[i-1][j], dp[i][j-1])) + 1;
}
}
}
return dp[m][n];
}
};