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 ));
}