• 动态规划——Edit Distance


    大意:给定两个字符串word1和word2,为了使word1变为word2,可以进行增加、删除、替换字符三种操作,请输出操作的最少次数
     

    Example 1:

    Input: word1 = "horse", word2 = "ros"
    Output: 3
    Explanation: 
    horse -> rorse (replace 'h' with 'r')
    rorse -> rose (remove 'r')
    rose -> ros (remove 'e')
    

    Example 2:

    Input: word1 = "intention", word2 = "execution"
    Output: 5
    Explanation: 
    intention -> inention (remove 't')
    inention -> enention (replace 'i' with 'e')
    enention -> exention (replace 'n' with 'x')
    exention -> exection (replace 'n' with 'c')
    exection -> execution (insert 'u')
    
     
    状态:dp[i][j]把word1[0..i-1]转换到word2[0..j-1]的最少操作次数
    状态转移方程:
      (1)如果word1[i-1] == word2[j-1],则令dp[i][j] = dp[i-1][j-1]
      (2)如果word1[i-1] != word2[j-1],由于没有一个特别有规律的方法来断定执行何种操作,在增加、删除、替换三种操作中选一种操作次数少的赋值给dp[i][j];
        增加操作:dp[i][j] = dp[i][j-1] + 1
        删除操作:dp[i][j] = dp[i-1][j] + 1
           替换操作:dp[i][j] = dp[i-1][j-1] + 1
     
     1 int minDistance(string word1,string word2){
     2     int wlen1 = word1.size();
     3     int wlen2 = word2.size();
     4     
     5     int**dp = new int*[wlen1 + 1];
     6     for (int i = 0; i <= wlen1; i++)
     7         dp[i] = new int[wlen2 + 1];
     8     
     9     //int dp[maxn][maxn] = { 0 };
    10     for (int i = 0; i <= wlen1; i++)
    11         dp[i][0] = i;
    12     for (int j = 0; j <= wlen2; j++)
    13         dp[0][j] = j;
    14     int temp = 0;
    15     for (int i = 1; i <= wlen1; i++){
    16         for (int j = 1; j <= wlen2; j++){
    17             if (word1[i - 1] == word2[j - 1])dp[i][j] = dp[i - 1][j-1];
    18             else{
    19                 temp = dp[i - 1][j - 1]<dp[i - 1][j] ? dp[i - 1][j - 1] : dp[i - 1][j];
    20                 temp = temp < dp[i][j - 1] ? temp : dp[i][j - 1];
    21                 dp[i][j] = temp + 1;
    22             }
    23         }
    24     }
    25 
    26     /*
    27     for (int i = 0; i <= wlen1; i++)
    28         delete[]dp[i];
    29     delete[]dp;
    30     */
    31 
    32     return dp[wlen1][wlen2];
    33 }
     
     
  • 相关阅读:
    逗号表达式
    Windows UninstallTool(右键卸载工具) 方便、快捷卸载电脑中的软件
    获取 Python 模块的路径
    Py2exe 打包后图标不显示[转载]
    获取系统文件关联图标
    py2exe 打包的exe,添加管理员权限
    获取注册表某键下的所有子键
    [已解决]Python脚本运行出错:libs\chardet\universaldetector.py:90: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode
    Git使用
    SQL Server获取指定行(如第二行)的数据
  • 原文地址:https://www.cnblogs.com/messi2017/p/9892109.html
Copyright © 2020-2023  润新知