# Recursive Methods as a Problem Solving Techique - Part 2

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

• The Problem of size N can be divided into:

1. A set of problems of size SMALLER than N

2. A problem X

• Each of The SMALLER problem MUST be identical in nature as Problem(N).

• Problem X MUST be solved easily using the set of solution for the SMALLER problems

• Solution is known for one or more base cases

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

• Baby rabbits grow into adults in one year
• Each year, a pair of adult (M/F) rabbits give birth to a pair of baby rabbits
• Sex of the pair of baby rabbits is M/F.
• Rabbits live forever...

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

3. The Fibonnaci Recurrence Relation:

• fn = fn-1 + fn-2
• Base case: f0 = 1
• Base case: f1 = 1

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: