逆向考虑:总长度-2*最长公共子序列长度。
class Solution {
public:
int minDistance(string word1, string word2) {
int size1 = word1.size(), size2 = word2.size();
int dp[size1+1][size2+1];
memset(dp, 0, sizeof(dp));
for (int i = 0; i < size1; i++) {
for (int j = 0; j < size2; j++) {
if (word1[i] == word2[j]) {
dp[i+1][j+1] = dp[i][j] + 1;
} else {
dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j]);
}
}
}
return size1+size2-2*dp[size1][size2];
}
};
正向考虑:dp[i][j]表示s[0:i]与t[0:j]的最小删除次数。
class Solution {
public:
int minDistance(string word1, string word2) {
int size1 = word1.size(), size2 = word2.size();
int dp[size1+1][size2+1];
memset(dp, 0, sizeof(dp));
for (int i = 1; i <= size1; i++) {
dp[i][0] = i;
}
for (int j = 1; j <= size2; j++) {
dp[0][j] = j;
}
for (int i = 0; i < size1; i++) {
for (int j = 0; j < size2; j++) {
if (word1[i] == word2[j]) {
dp[i+1][j+1] = dp[i][j];
} else {
dp[i+1][j+1] = min(dp[i][j+1], dp[i+1][j]) + 1;
}
}
}
return dp[size1][size2];
}
};