Recursive Methods as a Problem Solving Techique - Part 2

  1. Recursion can be (more generally) used for solving problem that have the following characteristics:

  2. Example: Fibonacci Numbers or "How fast do rabbit multiply"...

    Question: How many pairs of rabbits are there after n years ?

  3. The Fibonnaci Recurrence Relation:

    Recursive solution for computing Fibonacci number fn:

  4. Recursive method that calculate Fibonacci numbers:

    Fibonacci:
    
       public static int fibonacci(int N)
       {
          int sol1, sol2;    // Contain solutions for the smaller problems
          int solX;		 // Contains solution for original problem.
    
          if (N == 0)
          {  // Base case 1
             return(1);          // Return solution
          }
          else if (N == 1)
          {  // Base case 2
             return(1);          // Return solution
          }
          else
          {  // Recursive solver
    
             sol1 = fibonacci(N-1);   // Solve smaller sub problem 1
             sol2 = fibonacci(N-2);   // Solve smaller sub problem 2
    
             solX = sol1 + sol2;      // How to use solutions from
    				  // the smaller problems to solve
    				  // the original problem
    
             return(solX);		  // Return the solution....
          }
       }
    
    
    

  5. How the recursion works:

    Example: Fibonacci(3)
    
    

  6. Demo programs: