72. 编辑距离
题目链接:72. 编辑距离
方法:回溯 / 动态规划
解题思路
代码
回溯写法
class Solution {
public:
int minDistance(string word1, string word2) {
int n = word1.length(), m = word2.length();
if (n == 0) return m;
if (m == 0) return n;
int cache[n][m]; memset(cache, -1, sizeof(cache));
function<int(int, int)> dfs = [&](int i, int j) -> int {
if (i < 0 && j < 0) return 0;
else if ((i < 0 && j >= 0) || (i >= 0 && j < 0)) return abs(i - j);
if (cache[i][j] != -1) return cache[i][j];
int res = 0;
if (word1[i] == word2[j]) res = dfs(i - 1, j - 1);
else {
res = min(min(dfs(i - 1, j), dfs(i, j - 1)), dfs(i - 1, j - 1)) + 1; // 操作一次
}
cache[i][j] = res;
return res;
};
return dfs(n - 1, m - 1);
}
};
dp写法
class Solution {
public:
int minDistance(string word1, string word2) {
int n = word1.length(), m = word2.length();
int cache[n + 1][m + 1];
for (int i = 0; i <= n; i ++ ) cache[i][0] = i;
for (int j = 0; j <= m; j ++ ) cache[0][j] = j;
for (int i = 1; i <= n; i ++ ) {
for (int j = 1; j <= m; j ++ ) {
if (word1[i - 1] == word2[j - 1]) cache[i][j] = cache[i - 1][j - 1];
else {
cache[i][j] = min(min(cache[i - 1][j], cache[i][j - 1]), cache[i - 1][j - 1]) + 1;
}
}
}
return cache[n][m];
}
};

浙公网安备 33010602011771号