- 分类: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:
- Insert a character
- Delete a character
- 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的
网友评论