Leetcode 72 编辑距离 二维DP

  寻找问题的递归结构有时很简单,有时又很难。以本题来说,绝对不属于简单的行列。

  问题的规模不是由单一的字符串长度决定,而是由两个字符串的长度共同决定。那么子问题的分割将由按长度的顺延变为两个字符串所有可能长度的笛卡尔积。

  子问题的数量和组合多到让人很难理清问题与子问题之间的关系。

  这种情况下,可以将目光从整体放到局部。对于每个字符来说,有三种可能的操作。那么将一个字符拿出来后,问题本身可以由三个子问题的组合来描述(对应对这个字符的三种操作)。

  JAVA:

复制代码
public final int minDistance(String word1, String word2) {
        int len1 = word1.length(), len2 = word2.length();
        int[][] cache = new int[len1][len2];
        return min(word1, word2, 0, 0, cache);
    }

    private final int min(String word1, String word2, int point1, int point2, int[][] cache) {
        if (point1 == word1.length()) {
            if (point2 < word2.length()) return word2.length() - point2;
            else return 0;
        }
        if (point2 == word2.length()) return word1.length() - point1;
        if (cache[point1][point2] != 0) return cache[point1][point2];
        int re = Integer.MAX_VALUE;
        if (word1.charAt(point1) == word2.charAt(point2)) {
            re = min(word1, word2, point1 + 1, point2 + 1, cache);
        } else {
            re = Math.min(min(word1, word2, point1 + 1, point2, cache), min(word1, word2, point1 + 1, point2 + 1,
                    cache));
            re = Math.min(re, min(word1, word2, point1, point2 + 1, cache));
            re++;
        }
        cache[point1][point2] = re;
        return re;
    }
复制代码

  JS:

复制代码
var minDistance = function (word1, word2) {
    let len1 = word1.length, len2 = word2.length, cache = new Array(len1);
    for (let i = 0; i < len1; i++) cache[i] = new Array(len2);
    return min(word1, word2, 0, 0, cache);
};

var min = function (word1, word2, point1, point2, cache) {
    if (point1 == word1.length) return word2.length - point2;
    if (point2 == word2.length) return word1.length - point1;
    if (cache[point1][point2]) return cache[point1][point2];
    let re = Number.MAX_VALUE;
    if (word1.charAt(point1) == word2.charAt(point2)) re = min(word1, word2, point1 + 1, point2 + 1, cache);
    else {
        re = Math.min(min(word1, word2, point1 + 1, point2, cache), min(word1, word2, point1, point2 + 1, cache));
        re = Math.min(re, min(word1, word2, point1 + 1, point2 + 1),cache);
        re++;
    }
    cache[point1][point2] = re;
    return re;
}
复制代码

 

posted @   牛有肉  阅读(73)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示