Use memoization to avoid recurrence

Source: Internet
Author: User
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:

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.