dpij为到i-1和j-1为止的最小操作次数,需要初始化;
dp[i][0] 表示i-1要想变成和-1一样的删除次数,删除次数= i ;
递推公式:
当i-1 = j-1 时,不需要删,所以dp[i][j] = dp[i-1][j-1];
不等时三种情况:
dp[i][j] = min(dp[i][j-1]+ 1,min(dp[i-1][j]+1, dp[i-1][j-1] +2 ) );
- class Solution {
- public:
- int minDistance(string word1, string word2) {
- vector
int >>dp(word1.size()+1,vector<int >(word2.size()+1, 0)); - // dpij为到i-1和j-1为止的最小操作次数
- for(int i = 0; i <=word1.size(); i++) dp[i][0] = i;
- // dp[i][0] 表示i-1要想变成和0一样的删除次数,删除次数=i
- for(int j = 0; j <=word2.size(); j++) dp[0][j] = j;
-
- for(int i = 1; i <= word1.size(); i++) {
- for(int j = 1; j <=word2.size(); j++) {
- if(word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1];
- else{
- dp[i][j] = min(dp[i][j-1]+ 1,min(dp[i-1][j]+1, dp[i-1][j-1] +2 ) );
- }
- }
- }
- return dp[word1.size()][word2.size()];
- }
- };
求最大字串,最后两个串的长度 - 2 * 最大字串长
- class Solution {
- public:
- int minDistance(string word1, string word2) {
- vector
int >>dp(word1.size()+1,vector<int >(word2.size()+1, 0)); - // dpij为到i-1和j-1为止的最长相同字串数字
-
-
- for(int i = 1; i <= word1.size(); i++) {
- for(int j = 1; j <=word2.size(); j++) {
- if(word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
- else{
- dp[i][j] = max(dp[i][j-1],dp[i-1][j] );
- }
- }
- }
- return (word1.size()+word2.size()) - 2*dp[word1.size()][word2.size()];
- }
- };
- class Solution {
- public:
- int minDistance(string word1, string word2) {
- vector
int >>dp(word1.size()+1,vector<int >(word2.size()+1, 0)); - // dpij为到i-1和j-1为止的最小操作次数
- for(int i = 0; i <=word1.size(); i++) dp[i][0] = i;
- // dp[i][0] 表示i-1要想变成和0一样的删除次数,删除次数=i
- for(int j = 0; j <=word2.size(); j++) dp[0][j] = j;
-
- for(int i = 1; i <= word1.size(); i++) {
- for(int j = 1; j <=word2.size(); j++) {
- if(word1[i-1] == word2[j-1]) dp[i][j] = dp[i-1][j-1];
- //相同时不操作
- else{
- //dp[i][j] = min(dp[i][j-1]+ 1,min(dp[i-1][j]+1, dp[i-1][j-1] +1) );
- dp[i][j] = min({dp[i][j-1]+ 1,dp[i-1][j]+1, dp[i-1][j-1] +1});
- //增:dp[i][j-1]或者dp[i-1][j]
- //删:删除一个等于另一个加一
- //改:等于改成word1[i-1] == word2[j-1],所以dp[i][j] = dp[i-1][j-1] + 1;
- //取这仨的最小值
- }
- }
- }
- return dp[word1.size()][word2.size()];
- }
- };