Use memoization to avoid recurrence
Consider the issue of Fibonacci;
A simple recursive method can be used to solve the problem of Fibonacci:
Int fib (N)
{
If (n = 0 | n = 1 ){
Return 1;
}
Else {
Return fib (n-2) + fib (n-1 );
}
}
Note: Here, we consider the Fibonacci series starting from 1. Therefore, the series looks like ,...
Note: From the recursive tree, we calculate the FIB (3) function twice and the FIB (2) function three times. This is the repeated calculation of the same function. If n is very large, FIB
This simple technology is called memoization and can be used in Recursion to increase the computing speed.
The code of the Fibonacci function memoization should look like the following:
Int calc_fib (int n)
{
Int Val [N], I;
For (I = 0; I <= N; I ++ ){
Val [I] =-1; // value of the first n + 1 Terms of the Fibonacci terms set to-1
}
Val [0] = 1; // value of Fib (0) is set to 1
Val [1] = 1; // value of Fib (1) is set to 1
Return fib (n, Val );
}
Int fib (int n, int * value)
{
If (value [N]! =-1 ){
Return Value [N]; // using memoization
}
Else {
Value [N] = fib (n-2, value) + fib (n-1, value); // computing the Fibonacci term
}
Return Value [N]; // returning the value
}
The red part of the code above does not know why it can be declared. arrays in Standard C and C ++ cannot be declared in that way. It may be extended using the compiler.
Below is what I wrote in C ++:
# Include <iostream>
# Include <algorithm>
# Include <iterator>
Using namespace STD;
Int fib (int n, int Val [])
{
If (Val [N]! =-1)
Return Val [N];
Else
{
Val [N] = fib (n-1, Val) + fib (n-2, Val );
Return Val [N];
}
}
Void cal_fib (int n)
{
Int * val = new int [n + 1];
For (INT I = 0; I <= N; I ++)
Val [I] =-1;
Val [0] = 0;
Val [1] = 1;
FIB (n, Val );
Copy (Val, Val + n + 1, ostream_iterator <int> (cout ,""));
Cout <Endl;
Delete [] Val;
}
Int main ()
{
For (INT I = 3; I <= 15; I ++)
Cal_fib (I );
}
The output result is as follows: