【重点!记忆化递归+DP】LeetCode 72. Edit Distance

LeetCode 72. Edit Distance

参考链接:https://zxi.mytechroad.com/blog/dynamic-programming/leetcode-72-edit-distance/
思路:
这里写图片描述
Solution1:
递归

// Author: Huahua
// Runtime: 13 ms
class Solution {
public:
    int minDistance(string word1, string word2) {
        int l1 = word1.length();
        int l2 = word2.length();
        d_ = vector<vector<int>>(l1 + 1, vector<int>(l2 + 1, -1));
        return minDistance(word1, word2, l1, l2);
    }
private:
    vector<vector<int>> d_;
    // minDistance from word1[0:l1-1] to word2[0:l2-1]
    int minDistance(const string& word1, const string& word2, int l1, int l2) {
        if (l1 == 0) return l2;
        if (l2 == 0) return l1;
        if (d_[l1][l2] >= 0) return d_[l1][l2];

        int ans;
        if (word1[l1 - 1] == word2[l2 - 1])
            ans = minDistance(word1, word2, l1 - 1, l2 - 1);
        else 
            ans = min(minDistance(word1, word2, l1 - 1, l2 - 1),
                  min(minDistance(word1, word2, l1 - 1, l2), 
                      minDistance(word1, word2, l1, l2 - 1))) + 1;

        return d_[l1][l2] = ans;        
    }
};

Solution2:
迭代

// Author: Huahua
// Runtime: 9 ms
class Solution {
public:
    int minDistance(string word1, string word2) {
        int l1 = word1.length();
        int l2 = word2.length();
        // d[i][j] := minDistance(word1[0:i - 1], word2[0:j - 1]);
        vector<vector<int>> d(l1 + 1, vector<int>(l2 + 1, 0));

        for (int i = 0; i <= l1; ++i)
            d[i][0] = i;
        for (int j = 0; j <= l2; ++j)
            d[0][j] = j;

        for (int i = 1; i <= l1; ++i)
            for (int j = 1; j <= l2; ++j) {
                int c = (word1[i - 1] == word2[j - 1]) ? 0 : 1;
                d[i][j] = min(d[i - 1][j - 1] + c, 
                              min(d[i][j - 1], d[i - 1][j]) + 1);
            }

        return d[l1][l2];
    }
};

PS:花花真牛逼。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值