Recursive Methods as a Problem Solving Techique

  1. Recursive Method:

    Example: direct recursive method
          public class myClass
          {
             ....
    	 public (static) ... recursiveMethod(...)
             {
    	    ...
    	    ...
    	    recursiveMethod(new set of parameters)
    	    ...
    	    ...
    	 }
          }
    

    Example: indirect recursive method
          public class myClass
          {
             ....
    	 public (static) ... recursiveMethod1(...)
             {
    	    ...
    	    ...
    	    recursiveMethod2(.....)
    	    ...
    	    ...
    	 }
    
    	 public (static) ... recursiveMethod2(...)
             {
    	    ...
    	    ...
    	    recursiveMethod1(.....)
    	    ...
    	    ...
    	 }
          }
    

  2. Recursion is extremely suitable for solving problem that have the following characteristics:

  3. Recursive problem solving technique:

    General structure of a Recursive Solution
          public ... recursiveSolve("problem N")
          {
    	 if ( "problem N" is a base case )
    	 {
    	    return( (known) solution for base case );
    	 }
    	 else
    	 {
    	    Split "problem N" into k smaller "problems < N" 
    		and a "problem X"
    
    	    sol_1 = recursiveSolve("smaller problem 1");
    	    sol_2 = recursiveSolve("smaller problem 2");
    	    ....
    	    sol_k = recursiveSolve("smaller problem k");
    
    	    solution = solve "problem X" using the solutions
    	               "sol_1", "sol_2", ..., "sol_k"
    
    	    return(solution);
    	 }
          }
    
    • The statements in this skeletal program must be customized for each problem
    • There is no "magic formula", use your wits...
      (study Mathematics will help you build wits)

  4. Example: factorial

    The recursive program:

    Recursive Method to find Factorial of integer N
       public class Numeric
       {
          public static int factorial(int N)
          {
    	 if ( N == 0 )
    	 {
    	    return( 1 );   // (known) solution for base case
    	 }
    	 else
    	 {
    	    int sol;
    	    int solX;
    
    	    sol = factorial(N-1);
    	    solX = N * sol;
    
    	    return(solX);
    	 }
          }
       }
    

  5. NOTE: The recursive solution depends heavily on the temporal dimension of local & parameter scoping

  6. Demo programs: