纯dp 解法, 唯一可以优化的就是空间复杂度了,以下代码没有优化。。。
class Solution: # @param {string} word1 # @param {string} word2 # @return {integer} def minDistance(self, word1, word2): m, n = len(word1), len(word2) if m*n == 0: return max(m,n) dp = [[0] * (n + 1) for i in range(0, m+1)] for i in range(0,m+1): dp[i][0] = i for j in range(0,n+1): dp[0][j] = j 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: dp[i][j] = 1 + min(dp[i-1][j-1], dp[i][j-1], dp[i-1][j]) return dp[m][n]
时间: 2024-11-09 00:46:58