Leetcode——72. 編輯距離

題目傳送門
推薦看這個題解很精彩
下面給出c++寫法
自頂向下

class Solution {
public:
    struct HashPair {
        size_t operator() (const pair<int, int> &a) const {
            return a.first * 1000007 + a.second;
        }
    };
    
    unordered_map<pair<int, int>, int, HashPair> record;

    int match(const string &w1, const string &w2, int p1, int p2) {
        auto it = record.find(make_pair(p1, p2));
        if(it != record.end()) { //該問題已經被求解,直接返回答案!
            return it->second;
        }
        if(p1 == 0) {
            return p2; //搜索到了葉子結點!直接可以獲得答案!
        }
        if(p2 == 0 ){
            return p1; //搜索到了葉子結點!直接可以獲得答案!
        }
        if(w1[p1-1] == w2[p2-1]) { //A[pa] == B[pb],無需操作,繼續求解子問題!
            int ans = match(w1, w2, p1-1, p2-1);
            record.insert(make_pair(make_pair(p1, p2), ans)); //記錄答案。
            return ans;
        }
        //替換策略
        int ans = match(w1, w2, p1-1, p2-1) + 1;
        //插入策略
        ans = min(match(w1, w2, p1, p2-1) + 1, ans);
        //刪除策略
        ans = min(match(w1, w2, p1-1, p2) + 1, ans);

        record.insert(make_pair(make_pair(p1, p2), ans)); //記錄答案。
        return ans;
    }

    int minDistance(string word1, string word2) {
        return match(word1, word2, word1.size(), word2.size()); //目標問題較大時,考慮分而治之!
    }
};

自底向上

class Solution 
{
public:
    int Min(int a, int b, int c) 
    {
       return min(a, min(b, c));
    }
    int minDistance(string word1, string word2) 
    {
        int length1=word1.length();
        int length2=word2.length();
        int dp[length1+1][length2+1];
        for (int i = 0; i <= length1; i++)
            dp[i][0] = i;
        for (int j = 1; j <= length2; j++)
            dp[0][j] = j;
        for (int i = 1; i <= length1; i++)
             for (int j = 1; j <= length2; j++)
                if (word1[i-1] == word2[j-1])
                    dp[i][j] = Min(
                        dp[i-1][j]+1,
                        dp[i][j-1]+1,
                        dp[i-1][j-1]
                    );
                else               
                    dp[i][j] = Min(
                        dp[i-1][j]+1,
                        dp[i][j-1]+1,
                        dp[i-1][j-1]+1
                    );
        return dp[length1][length2];
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章