Fibonacci series ---------- Dynamic Plan DP

Source: Internet
Author: User

N = 10 20 30 40 50 46 experience, feel, Run Time

# Include <stdio. h>
Int fib (int n)
{

If (n <= 1) return 1;
Else return fib (n-1) + fib (n-2 );
}
Int main ()
{
Int N;
Scanf ("% d", & N );
Printf ("% d \ n", FIB (n ));
}

 

 

 

First n = 10 20 30 40 50 46 experience, feel, Run Time

Resubmit the zjut 1029 timeout.

 

// Time limited exceeded

# Include <stdio. h>
Int fib (int n)
{

If (n <= 1) return 1;
Else return fib (n-1) + fib (n-2 );
}
Int main ()
{
Int N;
While (scanf ("% d", & n ))
Printf ("% d \ n", FIB (n ));
}

 

Normal Recursion

From top to bottom, from large to small

 Pure Recursion

// Accept

# Include <stdio. h>
Int fib [50] = {0, 1 };// Use tables
Void Init ()
{
Int I;
For (I = 2; I <50; I ++)// Pure recursive For Loop
FIB [I] = fib [I-1] + fib [I-2];// From top to bottom, because it is big and small
}


Int main ()
{
Int N;
Init ();
While (scanf ("% d", & n ))
Printf ("% d \ n", FIB [N]);
}

 

 

 

 Memory search

Before Recursive Computing, determine whether the previous calculation has been performed.

There is a small (array --- saved) to push the big

 

// Accept
# Include <stdio. h>// Memory-based search
Int A [50] = {0, 1 };
Int fib (int n)
{
If (n <= 2) return a [n] = 1; // 1 is assigned to a [n]// Return 1;

Else if (a [n] = 0) return a [n] = fib (n-1) + fib (n-2 );//Not countedCalculate right fib (n-1) + fib (n-2 ),,When saving a [n]
Else return a [n]; //Otherwise, it will be counted. Use it directly a [n].

}


Int main ()
{
Int N;

While (scanf ("% d", & N )! = EOF)
Printf ("% d \ n", FIB (n ));
}

 

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.