zoukankan      html  css  js  c++  java
  • 动态规划-最长公共子序列

    import java.util.*;
    import java.io.*;
    public class LCSsequence {
        public static void main(String arg[]){
            char[] x=new char[100];
            char[] y=new char[100];
            int i,m,n;
            int[][] c=new int[100][100];
            int[][] s=new int[100][100];
            Scanner input=new Scanner(System.in);
            String str1=input.nextLine();
            String str2=input.nextLine();
            for(i=0;i<str1.length();i++){
                x[i+1]=str1.charAt(i);
            }
            for(i=0;i<str2.length();i++){
                y[i+1]=str2.charAt(i);
            }
            m=str1.length();
            n=str2.length();
            LCSLength(x,y,m,n,c,s);
            LCS(m,n,x,s);
        }
        static void LCSLength(char x[] ,char y[],int m,int n, int c[][], int b[][]){
            int i,j;
            for(i=1;i<=m;i++) c[i][0]=0;
            for(i=1;i<=n;i++) c[0][i]=0;
            for(i=1;i<=m;i++)
                for(j=1;j<=n;j++){
                    if(x[i]==y[j]){
                        c[i][j]=c[i-1][j-1]+1;
                        b[i][j]=1;
                    }
                    else if(c[i-1][j]>=c[i][j-1]){
                        c[i][j]=c[i-1][j];
                        b[i][j]=2;
                    }
                    else{
                        c[i][j]=c[i][j-1];
                        b[i][j]=3;
                    }
                }
        }
        static void LCS(int i ,int j, char x[] ,int b[][])
        {
             if (i ==0 || j==0) return;
             if (b[i][j]== 1)
             {
                 LCS(i-1,j-1,x,b);
                  System.out.print(x[i]);
             }
             else if (b[i][j]== 2)
                  LCS(i-1,j,x,b);
              else LCS(i,j-1,x,b);
        }
    }

  • 相关阅读:
    async和await
    Promise
    初始flexbox
    制作一个slider动画
    初探React编程逻辑(结合业务需求)
    原型(prototype)和继承(inherit)
    什么是词法环境(lexical scope)
    typeScript是什么
    typeScript基础类型
    原型,原型链,call/apply
  • 原文地址:https://www.cnblogs.com/ljs-666/p/8005795.html
Copyright © 2011-2022 走看看