题目描述
动态规划组成部分一:确定状态
子问题
动态规划组成部分二:转移方程
动态规划组成部分三:初始条件和边界情况
动态规划组成部分四:计算顺序
Java代码实现:
public int minDistance(String word1, String word2) {
int m = word1.length();
int n = word2.length();
char[] ch1 = word1.toCharArray();
char[] ch2 = word2.toCharArray();
int[][] f = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++)
f[i][0] = i;
for (int j = 0; j <= n; j++)
f[0][j] =j;
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
if (ch1[i - 1] == ch2[j - 1])
f[i][j] = f[i - 1][j - 1];
else
f[i][j] = Math.min(Math.min(f[i][j - 1], f[i - 1][j]) + 1, f[i - 1][j - 1] + 1);
return f[m][n];
}