[JAVA Basics] Brief Analysis of Recursive Algorithms

concept:

[Recursive algorithm:] A recursive algorithm is to transform a problem into a sub-problem of a similar problem with a reduced scale, and then recursively call a function (or procedure) to represent the solution of the function.
[Recursive function:] A process (or function) calls itself directly or indirectly, and this process (or function) is called a recursive function.

Features:

Recursion is calling itself within a procedure or function.
When using a recursive strategy, there must be an explicit recursion end condition. Called recursive exit.
The implementation is simple, but the efficiency is relatively low.

Case:
public static  int qh(int i){
        int sum  ;
        if(i==1){
            return 1; 
        }else {
            sum=i+qh(i-1) ;
            return sum ; 
        }
    }

Use recursion to quickly sum:
Suppose we use a relatively small number as an example and we now find the sum of 1 to 4, i pass parameter 4
i=4 qh(4)=4+qh(3) ;
i=3 qh( 3)=3+qh(2) ;
i=2 qh(2)=2+qh(1) ;
i=1 qh(1)=1 ;
Look up in this way, after knowing the value of qh(1), then The corresponding values ​​and sums can be obtained respectively.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325789580&siteId=291194637