[Backtracking/DP]72. Edit Distance

  • 分类:Backtracking/DP
  • 时间复杂度: O(m*n)

72. Edit Distance

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  1. Insert a character
  2. Delete a character
  3. Replace a character

Example 1:

Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation: 
horse -> rorse (replace 'h' with 'r')
rorse -> rose (remove 'r')
rose -> ros (remove 'e')

Example 2:

Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation: 
intention -> inention (remove 't')
inention -> enention (replace 'i' with 'e')
enention -> exention (replace 'n' with 'x')
exention -> exection (replace 'n' with 'c')
exection -> execution (insert 'u')

代码:

DP解法:

class Solution:
    def minDistance(self, word1: 'str', word2: 'str') -> 'int':
        
        m=len(word1)
        n=len(word2)
        
        dp=[[0 for i in range(n+1)] for i in range(m+1)]
        
        for i in range(1,m+1):
            dp[i][0]=dp[i-1][0]+1
        for j in range(1,n+1):
            dp[0][j]=dp[0][j-1]+1
            
        for i in range(1,m+1):
            for j in range(1,n+1):
                if (word1[i-1]==word2[j-1]):
                    dp[i][j]=dp[i-1][j-1]
                else:
                    #                 replace     insert      delete
                    dp[i][j]=min(min(dp[i-1][j-1],dp[i][j-1]),dp[i-1][j])+1
        
        return dp[-1][-1]

记忆化递归解法:

class Solution:
    def minDistance(self, word1: 'str', word2: 'str') -> 'int':
        
        m=len(word1)
        n=len(word2)
        
        res=self.paths(word1,word2,m,n,{})
        
        return res
    
    def paths(self, word1, word2, m, n, memo):   
        if (m,n) in memo:
            return memo[(m,n)]
        
        else:
            #退出条件
            if m==0 or n==0:
                memo[(m,n)]=max(m,n)
                return memo[(m,n)]

            if word1[m-1]==word2[n-1]:
                memo[(m,n)]=self.paths(word1,word2,m-1,n-1,memo)
            else:
                memo[(m,n)]=1+min(self.paths(word1,word2,m-1,n-1,memo),min(self.paths(word1,word2,m-1,n,memo),self.paths(word1,word2,m,n-1,memo)))
                
            return memo[(m,n)]

讨论:

1.记忆化递归比DP快
2.如果实在不能在一个循环里搞对的话弄两个循环也是OK的

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目链接tag: Easy; Dynamic Programming; question  Given two w...
    xingzai阅读 1,410评论 0 1
  • 对于iOS 开发者来说,KVO(key-value-observing)的使用大家已经不再陌生,而且使用起来也是非...
    GlassHead阅读 2,548评论 0 0
  • 因为你的纯朴和美丽 打动了一颗似乎麻木的心 突发的灵感要为你写诗 那个大山里的女人 像一株清新脱俗的百合花 在迷蒙...
    爱心天使_3534阅读 5,774评论 0 9
  • 『我不是魔术师但我喜欢帽子。 也许你也喜欢帽子,特别是当帽子总能在我头上变出花样来,甚至幻想我的帽子里是不是天天都...
    春风与雾阅读 3,669评论 0 0
  • 早睡早起早锻练29/90,自然醒来的我,感觉特别舒服。虽然外面下着大雨,但是我仍然坚持在家里跑步。这次我分开锻练,...
    UsanaCrystal阅读 1,560评论 0 0