1. Fibonacci Sequence Realization ~
Recursive implementation:
int fib (int n)
{
if (n = = 1 | | | n = = 2) return
1;
else return
fib (n-1) + fib (n-2);
}
Non-recursive (iterative method) implementation:
int fib (int n)
{
int num1 = 1;
int num2 = 1;
int num3 = 1;
while (n > 2)
{
/*num3 = num1 + num2;
NUM1 = num2;
num2 = num3;*///above three sentences equivalent to the bottom two sentences, however, these three sentences should return num3
NUM1 = num1 + num2;
num2 = num1-num2;
n--;
}
return NUM1;
}
From the above two implementations we can see that recursive code is much simpler than recursion. But do you know the story behind recursion if we want to count
Counting the 40th Fibonacci number, the computer needs to compute many times: each recursive call triggers another two recursive calls, and the two recursive calls
Triggers a recursive call. When we compute FIB (10), FIB (3) is called 21 times, and this number can be deduced on paper. Too much overhead.
So, from the time and space complexity, or not recursive better ~
2. String reverse Order ~
Non-recursive implementations:
void reverse (char *left, char *right)
{while
(left < right)
{
char tmp = *left;
*left = *right;
*right = tmp;
left++;
right--
}
}
Recursive implementation:
void reverse_string (char* str)
{
int len = Strlen (str);
if (Len > 1)
{
char tmp = str[0];
Str[0] = str[len-1];
Str[len-1] = ' the ';
Reverse_string (++STR);
STR[LEN-1] = tmp;
}
}
Analysis: Non-recursive implementation method is much better than recursion, not recursive code easy to understand, recursive code implementation principle: When the string length is greater than 1, recursive
, place the first character in a temporary open space, the last character in the position of the first character, and then place the last character in the position clear
As the Terminator, when the recursion ends, place the temporary area variable at the end of the so-called string.