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 @ 2021-02-27 23:45  牛有肉  阅读(73)  评论(0编辑  收藏  举报