zoukankan      html  css  js  c++  java
  • 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;
    }

    当你看清人们的真相,于是你知道了,你可以忍受孤独
  • 相关阅读:
    centos、mac的grafana安装和简单使用
    通过k8s(Kubernetes)搭建jmeter的压测环境master-slave架构,实现弹性伸缩
    burpsuite破解版
    jvm调优
    火狐firefox、谷歌chrome等浏览器扩展、插件介绍
    关于Chrome谷歌浏览器开发者工具网络Network中返回无数据的问题
    微博登录过程分析
    SQL SERVER大话存储结构(4)_复合索引与包含索引
    千万级别数据表,单列索引和多列索引性能对比
    Showplan 逻辑运算符和物理运算符参考
  • 原文地址:https://www.cnblogs.com/niuyourou/p/14457795.html
Copyright © 2011-2022 走看看