1. 程式人生 > >第十八周 Leetcode 72. Edit Distance(HARD) O(N^2)DP

第十八周 Leetcode 72. Edit Distance(HARD) O(N^2)DP

blog http else true rep 猜想 col () 字符串

Leetcode72

看起來比較棘手的一道題(列DP方程還是要大膽猜想。。)

DP方程該怎麽列呢?

dp[i][j]表示字符串a[0....i-1]轉化為b[0....j-1]的最少距離

轉移方程分三種情況考慮 分別對應三中操作

因為只需要三個值就可以更新dp[i][j] 我們可以把空間復雜度降低到O(n)

  1. Replace word1[i - 1] by word2[j - 1] (dp[i][j] = dp[i - 1][j - 1] + 1 (for replacement));
  2. Delete word1[i - 1] and word1[0..i - 2] = word2[0..j - 1] (dp[i][j] = dp[i - 1][j] + 1 (for deletion)
    );
  3. Insert word2[j - 1] to word1[0..i - 1] and word1[0..i - 1] + word2[j - 1] = word2[0..j - 1] (dp[i][j] = dp[i][j - 1] + 1 (for insertion)).
    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]; 
        }
    }; 
    

      

第十八周 Leetcode 72. Edit Distance(HARD) O(N^2)DP