|
Define: fn = # pairs of rabbits in after n month
|
|
fn = fn-1 + fn-2
with:
f0 = 1
f1 = 1
|
|
|
int fibonacci( int n )
{
if ( n == 0 /* a base case */ )
{
return 1; // The readily available solution for this base case
}
else if ( n == 1 /* another base case */ )
{
return 1; // The readily available solution for this base case
}
else
{
/* ---------------------------------------------
Let someone else solve the smaller problems
fibonacci(n-1) and fibonacci(n-2)
--------------------------------------------- */
sol1 = fibonacci ( n−1 );
sol2 = fibonacci ( n−2 );
/* ---------------------------------------
Use the solutions sol1 and sol2
to solve my own problem:
--------------------------------------- */
mySol = sol1 + sol2;
return mySol;
}
}
|
public class Recurse2
{
public static int fibonacci( int n )
{
int sol1, sol2, solution; // Define variable...
if ( n == 0 /* the first base case */ )
{
return 1; // The readily available solution for this base case
}
else if ( n == 1 /* the second base case */ )
{
return 1; // The readily available solution for this base case
}
else
{
sol1 = fibonacci ( n-1 ); // Hire "fibonacci" to solve first smaller problem
sol2 = fibonacci ( n-2 ); // Hire "fibonacci" to solve second smaller problem
mySol = sol1 + sol2; // Use the solutions of the smaller problems
// to solve my own problem
return mySol;
}
}
}
|
How to run the program:
|
|
And you will learn the dynamic programming technique to make it run faster.