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; }
当你看清人们的真相,于是你知道了,你可以忍受孤独
分类:
数据结构与算法
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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语句:使用策略模式优化代码结构