• 72. Edit Distance


    https://leetcode.com/problems/edit-distance/description/

    DP

    class Solution {
    public:
        int minDistance(string word1, string word2) {
            int m = word1.length(), n = word2.length();
            vector<vector<int>> dp(m+1, vector<int>(n+1, INT_MAX));
            for (int i = 0; i <= m; i++)
                dp[i][0] = i;
            for (int j = 0; j <= n; j++)
                dp[0][j] = j;
            for (int i = 1; i <= m; i++)
                for (int j = 1; j <= n; j++) {
                    if (word1[i-1] == word2[j-1])
                        dp[i][j] = dp[i-1][j-1];
                    else
                        dp[i][j] = min(dp[i-1][j-1], min(dp[i][j-1], dp[i-1][j])) + 1;
                }
            return dp[m][n];
        }
    };

    递归 (bad performance, should change cache key to index [i,j] in the two words)

    class Solution {
    public:
        map<pair<string,string>, int> cache;
        int minDistance(string word1, string word2) {
            auto key = make_pair(word1, word2);
            if (cache.count(key))   return cache[key];
                
            if (word1 == word2) return 0;
            int idx = 0;
            while (word1[idx] == word2[idx])    idx++;
            if (idx == word1.length())  return word2.length() - idx;
            if (idx == word2.length())  return word1.length() - idx;
            int res = 1 + min(
                minDistance(word1.substr(idx+1),word2.substr(idx+1)),    // replace current
                min(
                    minDistance(word1.substr(idx+1),word2.substr(idx)),  // delete one from first
                    minDistance(word1.substr(idx),word2.substr(idx+1))   // delete one from second
                ));
            cache[key] = res;
            return res;
        }
    };
  • 相关阅读:
    GitHub里的Hello World!
    4 款消息队列软件产品大比拼(转)
    .net常用组件
    Dapper.NET使用(转)
    设置MYSQL允许用IP访问
    test1
    SQLServer 2008以上误操作数据库恢复方法——日志尾部备份(转)
    Quartz.NET配置
    Quartz CronTrigger配置
    Quartz CronTrigger最完整配置说明
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/8978481.html
Copyright © 2020-2023  润新知