Pregunta

I am trying to find the the Longest Common Sub-sequence between two things of type comparable. I have the algorithm down, but I could like to add these items to a list via a recursion method call, but I do not know how I would add the last item to the list this way.

Here is my code:

public static <E extends Comparable<E>>List<E> getLongestCommonSubSeq(
   List<E> x,
   List<E> y )
{
   int m = x.size() +1;
   int n = y.size() +1;
   String[][] b =new String [m][n]; 
   int[][] c = new int[m][n];
   for(int i=1;i<m;i++) {
      c[i][0] = 0;
   }
   for(int j = 0;j<n;j++) {
      c[0][j]= 0;
   }
   for(int i=1; i<m;i++) {
      for(int j=1;j<n;j++) {
         if(x.get(i).equals(y.get(j))) {
            c[i][j] = c[i-1][j-1]+1;
            b[i][j]="NW";
         }
         else if(c[i-1][j] >= c[i][j-1]) {
            c[i][j]=c[i-1][j];
            b[i][j]="N";
         }
         else {
            c[i][j] = c[i][j-1];
            b[i][j]= "W";
         }
      }
   }
   return getLCS( m,n, b, x );
}

public static <E extends Comparable<E>> List<E> getLCS(
   int        i,
   int        j,
   String[][] b,
   List<E>    x )
{
   if(i==0 || j ==0)
      return null;
   if(b[i][j].equals("NW")) {
      // This can't be done because add returns a boolean type
      return getLCS(i-1,j-1, b, x) .add(x.get(i));
   }
   if(b[i][j].equals("N")) {
      return getLCS(i-1,j, b, x);
   }
   if(b[i][j].equals("W")) {
      return getLCS(i, j-1, b, x);
   }
   return null;
}
¿Fue útil?

Solución

public static <E extends Comparable<E>>List<E> getLCS(int i, int j, String[][] b, List<E> x){
        List<E> ret = new ArrayList<E>();


        if(i==0 || j ==0)
            return ret;

        if(b[i][j].equals("NW")) {
            // This can't be done because add returns a boolean type

            ret=getLCS(i-1,j-1, b, x);
            ret.add(x.get(i));
        }else if(b[i][j].equals("N")) {
            ret = getLCS(i-1,j, b, x);
        }else if(b[i][j].equals("W")) {
            ret= getLCS(i, j-1, b, x);
        }


        return ret;
    }

I was implementing it a little wrong

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top