Understanding and application of recursive algorithm

Source: Internet
Author: User

The recursive algorithm (recursion algorithm) in computer science refers to a method of solving a problem by repeatedly decomposing the problem into a homogeneous sub-problem.

The popular saying is that the big problem is equivalent to a small problem of the cycle of repetition, so by solving a small problem to achieve the purpose of solving large problems.

The loop repeats here, unlike the normal loop statement, which is reflected in the code as a self-invocation of the method.

As we all know, the cycle process must have a control condition to break the cycle, otherwise it will be infinite loop.

So, a scenario where recursive algorithms can be used and should be used, the individual is summed up as three points:

1. Large problem can be split to be equivalent to a small problem of cyclic repetition (must)

2. There are control conditions (known as exits) to disconnect self-invocation, or to continue self-invocation, the control condition is not necessarily a simple judgment statement, there can be many situations or multiple conditions (must)

3. The result of a self-invocation should be the initial value of the next call

Let's take a look at a few examples, and compare the use of recursive algorithms and the differences in recursion without using recursion.

1. Factorial

        //N (n-1) * (n-1-1) * (n-1-1-1) ...//Parse N * (n-1) * (n-1-1)//the process of factorial is summed up as a repetition of a multiplication operation * (n-1)         Public Static DoubleFactorialwithrecursion (intN) {varresult =1; inttemp; if(N >1) {result= n * (n-1); {Temp= N-1; if(Temp >1)//you can see that it is a repeating process that can be seen as an expansion of a recursive method call.{result= result * (Temp-1); Temp= Temp-1; if(Temp >1) {result= result * (Temp-1); Temp= Temp-1; if(Temp >1) {result= result * (Temp-1);//you can draw out repetitive code and write a method.                                ...                            } }                    }                }                returnresult; }            Else             {                returnresult; }        }

After extracting the duplicated code, it can be improved as follows.

         Public Static DoubleFactorialwithrecursion (intN) {if(N >1)//Clear Termination conditions{console.write (n+"*"); returnn * factorialwithrecursion (N-1); }            Else //The point at which the self-looping call is broken when the termination condition is not met{Console.WriteLine (1); return 1; }        }

2. The most classic recursion problem, Fibonacci sequence.

Description: Fibonacci Series 1, 1, 2, 3, 5, 8, 13, 21, 34

The Fibonacci sequence is defined by a recursive method as follows: F (1) =1,f (2) =1, f (n) =f (n-1) +f (n-2)

Simply put, when n>=2, the current number is the result of adding the first two values.

        /// <summary>        ///         /// </summary>        /// <param name= "Targetnumberindex" >Specify the Fibonacci sequence number</param>        /// <param name= "Previous" >the value of the previous number</param>        /// <param name= "Currentresult" >Current Cumulative result</param>        /// <param name= "Currentnumberindex" >current cumulative to the first few</param>        /// <returns></returns>         Public Static DoubleFibonacciwithrecursion (intTargetnumberindex,intPrevious =1,intCurrentresult =1,intCurrentnumberindex =2)        {
if(Targetnumberindex >2&& Currentnumberindex <=Targetnumberindex) {Currentnumberindex+=1; Console.WriteLine (Currentresult); vartemp =Currentresult; Currentresult= Currentresult +previous; returnfibonacciwithrecursion (Targetnumberindex, temp, currentresult, currentnumberindex); } Else { return 1; } }

Here is a forward thinking, i.e. f (n) = f (n-1) +f (n-2). is not a good implementation, but easy to understand.

The process of repeating calls is summed up as result = previous + result;

In this example, I have shown the 3rd, the result of a function call, the initial value of the next function call.

3. Application Questions

Title: One man drove the Ducks to every village to sell, and every village sold one half of the Ducks he drove. So he had two ducks left after seven villages and asked him how many ducks he had to drive out?

1. First, we find that there is a phrase in the title "One half of the ducks that have been chased through a village", and it is clear that this is a repeating process.

2. In the analysis of the above sentence, "sell one half of the ducks in the Chase", which shows the repetition of the calculation, but there are two ways of thinking:

1) Calculate the number of ducks sold, y=x/2+1;

2) Calculate the remaining number of ducks, y=x/2-1;

3. "After seven villages, there are two ducks, ask him how many ducks to set out", can be concluded that this is a result of the introduction of initial conditions.

Suppose initially there are X ducks, the equation for [(x/2-1)/2-1]/2-1...= 2; The repeat process is result = (RESULT/2-1), and the exit is the number of repetitions until the number of days is zero

If the initial conditions are introduced from the results, the equation can be written as, [(2+1) *2+1]*2 +1 ... = x; The repeat process is result = (result*2 + 1), the exit is a repeating number of days until the number of days is equal to the number of days given 7

Readers can try to achieve these two different ways by themselves.

Finally, I enclose a picture of the recursive process of self-control.

The idea of various algorithms, is always the necessary weapon of the program ape.

Understanding and application of recursive algorithm

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.