Leetcode No.72 ***

给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 。

你可以对一个单词进行如下三种操作:

  1. 插入一个字符
  2. 删除一个字符
  3. 替换一个字符

示例 1:

输入: word1 = "horse", word2 = "ros"
输出: 3
解释: 
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')

示例 2:

输入: word1 = "intention", word2 = "execution"
输出: 5
解释: 
intention -> inention (删除 't')
inention -> enention (将 'i' 替换为 'e')
enention -> exention (将 'n' 替换为 'x')
exention -> exection (将 'n' 替换为 'c')
exection -> execution (插入 'u')

参考了博客:http://www.cnblogs.com/grandyang/p/4344107.html

解答:因为不确定各种操作会对后面的影响,所有在比较时需要尝试三种操作。若word1[i]和word2[j]相同,则进入到下一位置,若不相同,依次进行三种操作:
【1】插入 word2[j],比较word1[i]和word2[j+1];
【2】删除 word2[j],比较word1[i]和word2[j];
【3】修改 word1[i] 为 word2[j],比较word1[i+1]和 word2[j+1];
为了去掉重复计算,利用数组memo保存当前计算状态。


//72
int minDistanceHelper(string& word1, int i, string& word2, int j,vector<vector<int>>& memo)
{
    if(i == word1.size()) return word2.size()-j;
    else if(j == word2.size()) return word1.size()-i;
    else if(memo[i][j] > 0) return memo[i][j];

    if(word1[i] == word2[j]) return minDistanceHelper(word1, i+1, word2, j+1, memo);
    else
    {
        int insertCnt = minDistanceHelper(word1, i, word2, j+1, memo);
        int deleteCnt= minDistanceHelper(word1,i+1, word2, j,memo);
        int replaceCnt = minDistanceHelper(word1, i+1, word2, j+1, memo);
        memo[i][j] = min(insertCnt,min(deleteCnt,replaceCnt))+1;
    }
    return memo[i][j];
}

int minDistance(string word1, string word2)
{
    int m = word1.size();
    int n = word2.size();
    vector<vector<int>> memo(m,vector<int>(n,0));
    return minDistanceHelper(word1,0,word2,0,memo);
}//72

 

posted @ 2019-05-08 21:39  andyalgorithm  阅读(202)  评论(0编辑  收藏  举报