编辑距离解决与0 (n)空间的问题
edit distance solution with O(n) space issue
找到了几个不同的解决方案并进行了调试,特别感兴趣的是下面的解决方案,它只需要O(n)空间,而不需要存储一个矩阵(M* n)。但是对cur[i]的逻辑意义感到困惑。如有任何意见,我将不胜感激。
我张贴了解决方案和代码。
Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
class Solution {
public:
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];
}
};
您可以将cur
视为编辑距离矩阵中前一行和当前行的混合。例如,在原始算法中考虑一个3x3矩阵。我将给每个位置编号,如下所示:
1 2 3
4 5 6
7 8 9
在循环中,如果计算位置6
,则只需要2
, 3
和5
的值。在这种情况下,cur
将恰好是来自:
4 5 3
看到最后的3
了吗?那是因为我们还没有更新它,所以它仍然有第一行的值。从之前的迭代中,我们得到了pre = 2
,因为它是在我们计算值为5之前保存的。
那么,最后一个单元格的新值是pre = 2
, cur[i-1] = 5
和cur[i] = 3
的最小值,正是前面提到的值。
编辑:完成类比,如果在O(n^2)版本中您计算min(M[i-1][j-1], M[i][j-1], M[i-1][j])
,那么在这个O(n)版本中您将分别计算min(pre, cur[i-1], cur[i])
。
相关文章:
- 如何在不使用额外空间的情况下解决这个问题?
- 有关命名空间和模板参数的名称的问题
- 命名空间范围问题
- 在 c++ 中定义命名空间中模板类的友元函数时出现问题
- OPENCV在C /名称空间问题上
- C++相同的命名空间问题
- C++11 中的命名空间问题?
- C++中的编译错误可能是命名空间问题
- 命名空间问题:前向声明和混合命名空间
- C++命名空间问题
- 空间问题
- LLVM设置函数传递的问题-命名空间问题
- C++中的命名空间问题
- 如何解决此命名空间问题
- C++编译器错误;我想是命名空间问题
- 名称空间问题
- c++ python构造函数类型错误(可能的命名空间问题)
- 如何避免juice框架和OpenCV之间的干扰命名空间问题
- 枚举的命名空间问题
- 动态二维阵列:空间问题