目录
题目链接:力扣
做动态规划就是要一直想着dp数组是什么含义
dp[i][j]:以i-1为结尾的字符串word1,和以j-1位结尾的字符串word2,想要达到相等,所需要删除元素的最少次数
有两种情况:
从递推公式中,可以看出来,dp[i][0] 和 dp[0][j]是一定要初始化的
dp[i][0]:word2为空字符串,以i-1为结尾的字符串word1要删除多少个元素,才能和word2相同呢,所以dp[i][0] = i
dp[0][j]:word1为空字符串,以i-1为结尾的字符串word2要删除多少个元素,才能和word1相同呢,所以dp[0][j] = j
从前向后,从上到下
- class Solution {
- public int minDistance(String word1, String word2) {
-
- int word1len = word1.length();
- int word2len = word2.length();
-
- // 创建dp数组
- int[][] dp = new int[word1len + 1][word2len + 1];
-
- // 初始化dp数组
- for (int i = 0; i < word1len + 1; i++) {
- dp[i][0] = i;
- }
- for (int j = 0; j < word2len + 1; j++) {
- dp[0][j] = j;
- }
-
- // 推导dp数组
- for (int i = 1; i < word1len + 1; i++) {
- for (int j = 1; j < word2len + 1; j++) {
- if (word1.charAt(i-1) == word2.charAt(j-1)) {
- dp[i][j] = dp[i-1][j-1];
- } else {
- dp[i][j] = Math.min(dp[i-1][j]+1,dp[i][j-1]+1);
- }
- }
- }
-
- return dp[word1len][word2len];
- }
- }
题目链接:力扣
dp[i][j] 表示以下标i-1为结尾的字符串word1,和以下标j-1为结尾的字符串word2,最近编辑距离为dp[i][j]
- if (word1[i - 1] == word2[j - 1])
- 不操作
- if (word1[i - 1] != word2[j - 1])
- 增
- 删
- 换
- if (word1[i - 1] == word2[j - 1]) {
- dp[i][j] = dp[i - 1][j - 1];
- }
- else {
- dp[i][j] = min({dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]}) + 1;
- }
dp[i][0] :以下标i-1为结尾的字符串word1,和空字符串word2,最近编辑距离为dp[i][0]。那么dp[i][0]就应该是i
dp[0][j]:以下标j-1为结尾的字符串word2,和空字符串word1,最近编辑距离为dp[0][j]。那么dp[0][j]就应该是j
从前向后,从上到下
- class Solution {
- public int minDistance(String word1, String word2) {
- int m = word1.length();
- int n = word2.length();
-
- // 创建dp数组
- int[][] dp = new int[m+1][n+1];
-
- // 初始化dp数组
- for (int i = 1; i <= m; i++) {
- dp[i][0] = i;
- }
- for (int i = 1; i <= n; i++) {
- dp[0][i] = i;
- }
-
- // 推导dp数组
- for (int i = 1; i <= m; i++) {
- for (int j = 1; j <= n; j++) {
- int left = dp[i][j-1] + 1;
- int mid = dp[i-1][j-1];
- int right = dp[i-1][j] + 1;
- if (word1.charAt(i-1) != word2.charAt(j-1)) {
- mid++;
- }
- dp[i][j] = Math.min(left,Math.min(mid,right));
- }
- }
-
- return dp[m][n];
- }
-
- }