编辑距离算法

这是个很经典的动态规划题目(可惜我每次都只明白原理,却不知道怎么写).

主要概念:https://www.jianshu.com/p/46ff18e8d636

题目链接:https://leetcode-cn.com/problems/edit-distance/

 1 class Solution {
 2 public:
 3     int minDistance(string word1, string word2) {
 4         int length1=word1.size();int length2=word2.size();
 5         int dp[length1+1][length2+1]={0};
 6         for(int i=0;i<=length1;i++) dp[i][0]=i;
 7         for(int j=0;j<=length2;j++) dp[0][j]=j;
 8         for(int i=1;i<=length1;i++)
 9             for(int j=1;j<=length2;j++)
10             {
11                 if(word1[i-1]==word2[j-1]) 
12                     dp[i][j]=min(min(dp[i-1][j],dp[i][j-1])+1,dp[i-1][j-1]);
13                 else 
14                     dp[i][j]=min(min(dp[i-1][j],dp[i][j-1])+1,dp[i-1][j-1]+1);
15             }
16         return dp[length1][length2];
17     }
18 };

目前对动态规划的题目终于有点认识了,不过还需要接着练习很多题,才能明白这种思想

猜你喜欢

转载自www.cnblogs.com/pppyyyzzz/p/11910581.html
今日推荐