编辑距离解决与0 (n)空间的问题

edit distance solution with O(n) space issue

本文关键字:空间 问题 解决 编辑距离      更新时间:2023-10-16

找到了几个不同的解决方案并进行了调试,特别感兴趣的是下面的解决方案,它只需要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, 35的值。在这种情况下,cur将恰好是来自:

的值
4 5 3

看到最后的3了吗?那是因为我们还没有更新它,所以它仍然有第一行的值。从之前的迭代中,我们得到了pre = 2,因为它是在我们计算值为5之前保存的。

那么,最后一个单元格的新值是pre = 2, cur[i-1] = 5cur[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])