Advertisement
tendua

Longest Increasing Subsequence - Recursion Method

Jul 24th, 2012
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.22 KB | None | 0 0
  1.  
  2. //      Longest Increasing Sub-Sequence problem
  3. //      Naive recursion method. Complexity O(2^n);
  4. //      Wed Jul 25 01:09:10 IST 2012
  5.  
  6. import java.util.StringTokenizer;
  7. import java.io.BufferedReader;
  8. import java.io.IOException;
  9. import java.io.InputStreamReader;
  10.  
  11. class longestSubSequence{
  12.     public static void main (String [] args)throws IOException{
  13.         new longestSubSequence().run();
  14.     }
  15.  
  16.     int max = -1;
  17.     int index = 1;
  18.     int [] array;
  19.     private void run() throws IOException{
  20.         array = new int [50];
  21.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  22.         StringTokenizer st = new StringTokenizer (br.readLine());
  23.         array[0] = -1;
  24.         while (st.hasMoreTokens()){
  25.                 array[index++] = Integer.parseInt(st.nextToken());
  26.         }
  27.         index--;
  28.         dfs (0,0);
  29.         System.out.println(max);//      Prints the maximum length
  30.     }
  31.  
  32.     private void dfs (int curr, int length){
  33.         if (length > max )max = length;
  34.         if (curr >= index)
  35.             return ;
  36.         for (int I=curr+1;I <= index; I++){
  37.             if (array[I] >= array[curr]){
  38.                 dfs (I, length+1);
  39.             }
  40.         }
  41.     }
  42. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement