recursive algorithm: is an algorithm that calls itself directly or indirectly. The
implementation procedure: completes recursively by writing code directly or indirectly to itself in a function or a subroutine, through a function or a child process. (The same category of problems, the problem layer into a small scale of the problem to the smallest problem has known conditions, and then to solve, and then get the results of stepwise return.) is actually a kind of circulation.
Most Important: the small amount of code solves a very complex problem.
Features:
1, recursion is the method call itself
2, must have a definite recursive end condition, called recursive exit.
3, concise but inefficient operation, generally do not advocate the use of
4, each layer of the return point, local variables such as the stack to store, too many recursive times can cause stack overflow.
Instance 1: Factorial
C + + code:
The code is as follows |
Copy Code |
#include <iostream> int factorial (int n); int main () { using namespace Std; int n; cout << "Please enter a number:"; CIN >> N; cout << n << "factorial is:" << factorial (n) <<endl; return 0; } int factorial (int n) { if (n = = 1) return 1; Return n*factorial (n-1); } |
Example 2: The conversion of the numbering
Code:
The code is as follows |
Copy Code |
#include <iostream> #include <cstring> void Feelthebase (char *s, int n, int sys); int main () { using namespace Std; Char s[60]; int N,sys; cout << "Please enter an integer:"; CIN >> N; cout << "Please enter the type of import (2,8,16) to convert:"; CIN >> SYS; Feelthebase (s, N, SYS); cout << n << "convert to" << sys << "The result is:" << s <<endl; return 0; } void Feelthebase (char *s, int n, int sys) { Char bit[] = {"0123456789ABCDEF"}; int Len; if (n = = 0) { strcpy (S, ""); Return } Feelthebase (S, N/sys, SYS); Len = strlen (s); S[len] = Bit[n%sys]; S[len+1] = '; } |
Example 3: List all subdirectories and files in a directory (and can be more convenient with the Scandir function)
PHP Implementation code:
The code is as follows |
Copy Code |
<?php Function Rec ($dir, $lev =0) { $DH = Opendir ($dir); while (($file = Readdir ($DH))!= false) { if ($file = = '. ' | | $file = = ' ... ') { Continue } if (Is_dir ($dir. '/'. $file)) { $arr = Explode ("/", $dir. '/'. $file); $lev = count ($arr)-3; Echo Str_pad (", $lev,"--")." Directory ". $file." <br/> "; Rec ($dir. '/'. $file, $lev + 1); }else { Echo Str_pad (", $lev,"--"). $file." <br/> "; } }
Closedir ($DH); } $dir = "./"; Rec ($DIR); ?> |
Run Result: