首页 > 代码库 > 第十八周 Leetcode 72. Edit Distance(HARD) O(N^2)DP
第十八周 Leetcode 72. Edit Distance(HARD) O(N^2)DP
Leetcode72
看起来比较棘手的一道题(列DP方程还是要大胆猜想。。)
DP方程该怎么列呢?
dp[i][j]表示字符串a[0....i-1]转化为b[0....j-1]的最少距离
转移方程分三种情况考虑 分别对应三中操作
因为只需要三个值就可以更新dp[i][j] 我们可以把空间复杂度降低到O(n)
- Replace
word1[i - 1]
byword2[j - 1]
(dp[i][j] = dp[i - 1][j - 1] + 1 (for replacement)
); - Delete
word1[i - 1]
andword1[0..i - 2] = word2[0..j - 1]
(dp[i][j] = dp[i - 1][j] + 1 (for deletion)
); - Insert
word2[j - 1]
toword1[0..i - 1]
andword1[0..i - 1] + word2[j - 1] = word2[0..j - 1]
(dp[i][j] = dp[i][j - 1] + 1 (for insertion)
).class Solution { public: int minDistance(string word1, string word2) { int m = word1.length(), n = word2.length(); vector<int> cur(m + 1, 0); for (int i = 1; i <= m; i++) cur[i] = i; for (int j = 1; j <= n; j++) { int pre = cur[0]; cur[0] = j; for (int i = 1; i <= m; i++) { int temp = cur[i]; if (word1[i - 1] == word2[j - 1]) cur[i] = pre; else cur[i] = min(pre + 1, min(cur[i] + 1, cur[i - 1] + 1)); pre = temp; } } return cur[m]; } };
第十八周 Leetcode 72. Edit Distance(HARD) O(N^2)DP
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。