[leetcode DP]72. Edit Distance
计算最少用多少不把word1变为word2,
思路:建立一个dp表,行为word1的长度,宽为word2的长度
1.边界条件,dp[i][0] = i,dp[0][j]=j
2.最优子问题,考虑已经知道word1[0:i-1]转变为word2[0:j-1]的次数,只需要考虑word1[i]和word[j]的情况
3.子问题重叠,word1[i]和word2[j]是否相等,每种情况下怎样有最少步骤
1 class Solution(object): 2 def minDistance(self, word1, word2): 3 d1,d2 = len(word1),len(word2) 4 dp = [[0 for j in range(d2+1)] for i in range(d1+1)] 5 for i in range(d1+1): 6 dp[i][0] = i 7 for j in range(d2+1): 8 dp[0][j] = j 9 for i in range(1,d1+1): 10 for j in range(1,d2+1): 11 if word1[i-1] == word2[j-1]: 12 dp[i][j] = dp[i-1][j-1] 13 else: 14 dp[i][j] = min(dp[i][j-1],dp[i-1][j-1],dp[i-1][j])+1 15 return dp[d1][d2] 16