Recursive algorithm analysis and strategy of divide and conquer

Recursion and divide and conquer strategy

Calls itself directly or indirectly algorithm is called recursive algorithm. Function definition given recursive function called by the function itself.
In the design and analysis computer algorithm, a recursive technique tends to make the definition and description of the function of the algorithm is simple and easy to understand.

Example 1 factorial function

Can be defined recursively as:
where:
n-when = 0, n = 1 is the boundary conditions!
N-> when 0, n = n (n-1 ) is a recursive equation!!
Boundary condition equations with recursive elements are two recursive function recursive function only with these two elements, in order to obtain the result after a finite number of calculations.

Example 2 Fibonacci Number
infinite series 1,1,2,3,5,8,13,21,34,55, ..., is referred to Fibonacci sequence. It can be defined recursively as:
n-th Fibonacci number may be calculated recursively as follows:
int fibonacci(int n){
       if (n <= 1) return 1;
       return fibonacci(n-1)+fibonacci(n-2);
   }

 

Recursive need to have the boundary conditions, recursive and recursive return of the advance period.
When the boundary condition is not satisfied, recursive forward;
when the boundary conditions are met, the recursive return.
Note: When using incremental Reduction Strategy, there must be a clear recursive end condition, called recursive exports, or they will go on unlimited (deadlock).
Recursive shortcomings:
a lower problem solving recursive algorithm operational efficiency.
In the course of the recursive call, the system returns to the point of each layer, local variables, and so opened up the stack to store. Recursive too many times likely to cause a stack overflow.

Each digit output a reverse positive number 3 in the embodiment of

example, to the number 12345, sequentially outputs 54321
Analysis: n / 10 == 0, n output; otherwise the output n% 10, then, for n / 10 performs the same process
void Reverse( int n){
	if(n/10==0)
  		cout<<n;
  else{
		cout<<n%10;
		Reverse(n/10);
   }
}
main(){
    Reverse(12345);
}

 

 
Each digit sequentially outputs a positive number of
For example, the number 12345, sequentially outputs 12345
Analysis: If n / 10 == 0, then the n-output; otherwise, after the first of the n / 10 subjected to the same treatment, cout << n% 10;
void Reverse( int n){
	if(n/10==0)
  		cout<<n;
  else{
		Reverse(n/10);
		cout<<n%10;
   }
}
main(){
    Reverse(12345);
}

 

Guess you like

Origin www.cnblogs.com/khnl/p/11639258.html