leetcode72+ 最小编辑距离,DP二维数组上求

https://leetcode.com/problems/edit-distance/description/

class Solution {
public:
    int minDistance(string word1, string word2) {
        int len1 = word1.size(), len2 = word2.size();
        vector< vector<int>> f(len1+1, vector<int>(len2+1));
        for(int i=0; i<=len1; i++) f[i][0] = i;
        for(int j=0; j<=len2; j++) f[0][j] = j;
        for(int i=1; i<=len1; i++){
            for(int j=1; j<=len2; j++){
                if(word2[j-1]==word1[i-1]) f[i][j] = f[i-1][j-1];
                else{
                    int tmp = min(f[i][j-1], f[i-1][j]);
                    f[i][j] = min(f[i-1][j-1], tmp)+1;
                }
            }
        }
        return f[len1][len2];
    }
};

word1[i]==word2[j] 这个不用想,我们就看不相等的,比如word1[i]后面添加一个字符等于word2[j],可以看出  word1[i]要添加一次操作,是因为word2[j]这个字符惹的祸,是word2[j-1]再来一次操作就是到  word2[j].所以f[i][j]= f[i][j-1]+1

猜你喜欢

转载自blog.csdn.net/u013554860/article/details/81173322