zoukankan      html  css  js  c++  java
  • [Algorithms] Using Dynamic Programming to Solve longest common subsequence problem

    Let's say we have two strings:

    str1 = 'ACDEB'

    str2 = 'AEBC'

    We need to find the longest common subsequence, which in this case should be 'AEB'.

    Using dynamic programming, we want to compare by char not by whole words.

    • we need memo to keep tracking the result which have already been calculated
      •   memo is 2d array, in this case is 5 * 4 array.
    • It devided problem into two parts
      •   If the char at the given indexs for both strings are the same, for example, 'A' for str1 & str2, then we consider 
    'A' + LSC(str1, str2, i1 + 1, i2 + 1)
      • If the char at the given indexs are not the same, we pick max length between LCB('DEB', 'EBC') & LCB('CDEB', 'BC'),  we pick
    Max {
       LCS('DEB', 'EBC'),
       LCS('CDEB', 'BC')
    }

    Bacislly for the str1 = 'CDEB' str2 = 'EBC', the first char is not the same, one is 'C', another is 'E', then we devide into tow cases and get the longer one. The way to devide is cutting 'C' from str1 get LCS('DEB', 'EBC'), and cutting 'E' from str2 get LCS('CDEB', 'BC').

     /**
     * FIND THE LONGEST COMMON SEQUENCES BY USING DYNAMICE PROGRAMMING
     *
     * @params:
     * str1: string
     * str2: string
     * i1: number
     * i2: number
     * memo: array []
     *
     * TC: O(L*M) << O(2^(L*M))
     */
    
    function LCS(str1, str2) {
        const memo = [...Array(str1.length)].map(e => Array(str2.length));
      
        /**
         * @return longest common sequence string
         */
        function helper(str1, str2, i1, i2, memo) {
          console.log(`str1, str2, ${i1}, ${i2}`);
          // if the input string is empty
          if (str1.length === i1 || str2.length === i2) {
            return "";
          }
          // check the memo, whether it contians the value
          if (memo[i1][i2] !== undefined) {
            return memo[i1][i2];
          }
          // if the first latter is the same
          // "A" + LCS(CDEB, EBC)
          if (str1[i1] === str2[i2]) {
            memo[i1][i2] = str1[i1] + helper(str1, str2, i1 + 1, i2 + 1, memo);
            return memo[i1][i2];
          }
      
          // Max { "C" + LCS(DEB, EBC), "E" + LCB(CDEB, BC) }
          let result;
          const resultA = helper(str1, str2, i1 + 1, i2, memo); // L
          const resultB = helper(str1, str2, i1, i2 + 1, memo); // M
      
          if (resultA.length > resultB.length) {
            result = resultA;
          } else {
            result = resultB;
          }
      
          memo[i1][i2] = result;
          return result;
        }
      
        return {
          result: helper(str1, str2, 0, 0, memo),
          memo
        };
      }
      
      //const str1 = "I am current working in Finland @Nordea",
      //str2 = "I am currently working in Finland at Nordea";
      
      const str1 = "ACDEB",
        str2 = "GAEBC";
      
      const { result, memo } = LCS(str1, str2);
      console.log(
        `
         ${str1}  
         ${str2}
         's longest common sequence is 
         "${result === "" ? "Empty!!!" : result}"
        `
      );
      
      console.log(memo);
      

    ----

    Bottom up solution can be:

    1. Init first row and first col value to zero

    2. Then loop thought the data, If row latter and col latter is not the same, then take which is larger Max {the previous row same col value data[row-1][col], same row but previous col data[row][col-1]}

    3. If they are the same, take data[row-1][col-1] + 1.

    Source, Code

  • 相关阅读:
    Excel表导入数据库时带小数点的数据会变成科学计数样式的解决方法
    C# 具有合计行的DataGridViewNiceDataGridView1.0
    nginx 【使用echo调试】【地址复写】
    ts 【申明文件】
    createreactapp 【引入ui框架样式,全局样式被处理成模块化样式处理方法】
    node 【node服务器搭建1:安转node 和pm2】
    http 【前后端缓存】【nginx配合缓存】
    nginx 【匹配规则】【开启gzip压缩】
    nginx【nginx配置】
    react 【useMome、useCallback原理详解】
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10206497.html
Copyright © 2011-2022 走看看