最短编辑距离,这么经典的DP问题我就不描述了。
解法就是在三种操作对应的代价中取最小作为下一状态值,值得一提的是评论区O(n)的优化。
Code-ordinary
int minDistance(string word1, string word2) { //1 as row, 2 as column
int row = word1.size(), column = word2.size();
vector<vector<int> > dp(row+1, vector<int>(column+1, 0));
for(int i = 0; i <= row; ++i) dp[i][0] = i;
for(int j = 0; j <= column; ++j) dp[0][j] = j;
for(int i = 1; i <= row; ++i)
for(int j = 1; j <= column; ++j) {
int a = dp[i-1][j] < dp[i][j-1] ? dp[i-1][j] : dp[i][j-1];
a++;
int b = word1[i-1] == word2[j-1] ? dp[i-1][j-1] : dp[i-1][j-1]+1;
dp[i][j] = a < b ? a : b;
}
return dp[row][column];
}
Code-optimized
When we update dp[i][j], we only need dp[i - 1][j - 1], dp[i][j - 1], dp[i - 1][j]. In fact, we need not maintain the full m*n matrix. Instead, maintaing one column is enough.
int minDistance(string word1, string word2) {
int m = word1.length(), n = word2.length();
vector<int> cur(m + 1, 0);
for (int i = 1; i <= m; i++)
cur[i] = i;
for (int j = 1; j <= n; j++) {
int pre = cur[0];
cur[0] = j;
for (int i = 1; i <= m; i++) {
int temp = cur[i];
if (word1[i - 1] == word2[j - 1])
cur[i] = pre;
else cur[i] = min(pre + 1, min(cur[i] + 1, cur[i - 1] + 1));
pre = temp;
}
}
return cur[m];
}