zoukankan      html  css  js  c++  java
  • LeetCode之“动态规划”:Edit Distance

      题目链接

      题目要求:

      Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

      You have the following 3 operations permitted on a word:

      a) Insert a character
      b) Delete a character
      c) Replace a character

      该题的解析宅自一博文

      我们维护的变量res[i][j]表示的是word1的前i个字符和word2的前j个字符编辑的最少操作数是多少。假设我们拥有res[i][j]前的所有历史信息,看看如何在常量时间内得到当前的res[i][j],我们讨论两种情况:
      1)如果word1[i-1]=word2[j-1],也就是当前两个字符相同,也就是不需要编辑,那么很容易得到res[i][j]=res[i-1][j-1],因为新加入的字符不用编辑;
      2)如果word1[i-1]!=word2[j-1],那么我们就考虑三种操作,如果是插入word1,那么res[i][j]=res[i-1][j]+1,也就是取word1前i-1个字符和word2前j个字符的最好结果,然后添加一个插入操作;如果是插入word2,那么res[i][j]=res[i][j-1]+1,道理同上面一种操作;如果是替换操作,那么类似于上面第一种情况,但是要加一个替换操作(因为word1[i-1]和word2[j-1]不相等),所以递推式是res[i][j]=res[i-1][j-1]+1。上面列举的情况包含了所有可能性,有朋友可能会说为什么没有删除操作,其实这里添加一个插入操作永远能得到与一个删除操作相同的效果,所以删除不会使最少操作数变得更好,因此如果我们是正向考虑,则不需要删除操作。取上面几种情况最小的操作数,即为第二种情况的结果,即res[i][j] = min(res[i-1][j], res[i][j-1], res[i-1][j-1])+1。

      程序大概流程图如下:

      

      程序如下:

     1 class Solution {
     2 public:
     3     int min(int a, int b, int c)
     4     {
     5         int tmp = (a < b) ? a : b;
     6         return (tmp < c) ? tmp : c;
     7     }
     8     
     9     int minDistance(string word1, string word2) {
    10         int szWord1 = word1.size();
    11         int szWord2 = word2.size();
    12         if(szWord1 == 0)
    13             return szWord2;
    14         if(szWord2 == 0)
    15             return szWord1;
    16         
    17         vector<vector<int> > dp(szWord1 + 1, vector<int>(szWord2 + 1, 0));
    18         for(int i = 0; i < szWord1 + 1; i++)
    19             dp[i][0] = i;
    20         for(int j = 0; j < szWord2 + 1; j++)
    21             dp[0][j] = j;
    22         
    23         for(int i = 1; i < szWord1 + 1; i++)
    24             for(int j = 1; j < szWord2 + 1; j++)
    25             {
    26                 if(word1[i-1] == word2[j-1])
    27                     dp[i][j] = dp[i-1][j-1];
    28                 else
    29                     dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1;
    30             }
    31         
    32         return dp[szWord1][szWord2];
    33     }
    34 };
  • 相关阅读:
    Python列表生成
    Python 多线程
    Python面向对象编程
    map, reduce和filter(函数式编程)
    35个高级python知识点
    python之pyc
    Python之简单的用户名密码验证
    EasyUI 实例
    hibernate映射文件one-to-one元素属性
    Java中多对多映射关系
  • 原文地址:https://www.cnblogs.com/xiehongfeng100/p/4580066.html
Copyright © 2011-2022 走看看