A ramble on recursion: the thought of recursion--reprint

Source: Internet
Author: User

Why use recursion

The basic algorithm for estimating the most confusing mind in programming is recursion. Many times we see that a complex recursion is a bit of a time-consuming problem, especially when the concept of a model is unclear, and it is more difficult to design a recursion yourself.

A lot of people do not understand recursion (today in CSDN see a beginner's message), always think that recursion is completely unnecessary, with the loop can be achieved, in fact, this is a very superficial understanding. Because recursion in the program can be swept not because of his cycle, we all know that recursion is divided into two steps, recursion and return, then you can know recursion for space performance, is simply commit, this for the pursuit of space-time perfect person, simply can not accept, if recursion is just a loop, estimated now we can not see recursion. Recursion now exists because recursion can produce an infinite loop, which means that it is possible to generate 100 or 10000 layers for loops. For example, for a string to be fully arranged, the string length is variable, then if you use the loop to implement, you will find that you do not write, this time to call recursion, and in the recursive model can also use branch recursion, such as for loop and recursive nesting, or this section enumerates several recursive stepping expressions, Each one forms a recursive.

Using inductive method to understand recursion

Mathematics is not bad for us, the first reaction is the recursive mathematical model is what. After all, we are much more adept at modeling problems than we do with code modeling. (Of course, if the problem is clear to the person can also direct resume recursive model, the use of digital modeling intermediary is for those who are not very clear about the problem)

Observing recursion, we will find that the recursive mathematical model is actually inductive, which is the most common in the high School series. Recall the inductive method.

Inductive method is applied to solve a problem to solve his sub-problem, and his sub-problem becomes sub-problem, and we found that these problems are actually a model, that is, there is the same logical induction processing items. Of course there is an exception, that is, which of the recursive end of the processing method does not apply to our inductive processing items, of course, we can not apply, otherwise we will be infinite recursion. This leads to an inductive endpoint and an expression for direct solution. If you use a list to describe the inductive method is:

    • Step expression: An expression of problems transforming into sub-problems
    • End condition: When you can no longer use a stepping expression
    • Direct solution expression: An expression that evaluates the return value directly under the end condition
    • Logical Induction: Applies to all non-applicable to the end of the sub-problem of processing, of course, the above step expression is actually contained in the face.

This is actually the end, and the recursion comes out. The general form of the recursive algorithm:

void func (mode) {    if(endcondition)    {        constexpression         // Base Item      }    else    {        accumrateexpreesion     // Inductive Items        Mode=expression         // Step-expression            func (mode)          // call itself, recursive     }}

The most typical is the n! algorithm, which is the most persuasive. Understand the idea of recursion and use of the scene, the basic can be designed by themselves, of course, and other algorithms to use, but also need to continue to practice and summary.

#include"stdio.h"#include"math.h"intMainvoid){    intN, RS; printf ("Please enter the number of factorial to calculate N:"); scanf ("%d",&N); RS=factorial (n); printf ("%d", RS);}//Recursive calculation processintfactorial (n) {if(n = =1) {          return 1; }     returnn * Factorial (n1);}

The recursion of factorial is relatively simple, it is not unfolded here.

#include "stdio.h" #include "math.h" int main (void) {    int n, RS;    printf ("Please enter the number of factorial to be calculated n:");    scanf ("%d", &n);    rs = factorial (n);    printf ("%d", RS);} Recursive calculation procedure int factorial (n) {     if (n = = 1) {          return 1;     }     return n * factorial (n-1);}

  

Another example of two recursion

Returns the depth of a binary tree:

int Depth (Tree t) {      ifreturn0;      Else {         int a=Depth (t.right);          int b=Depth (t.left);          return (a>b)? (A +1):(B +1);     } }

Determine whether a binary tree is balanced:

intIsB (Tree t) {if(!t)return 0; intleft=IsB (T.left); intright=IsB (t.right); if(Left >=0&& Right >=0&& Left-right <=1|| Left-right >=-1)         return(Left < right)? (Right +1): (left +1); Else return-1; } 

The first algorithm is better understood, but the second one is not so well understood. The idea of the first algorithm is that if the tree is empty, it returns 0, otherwise the depth of the left tree is obtained, then the depth of the right number is obtained, and then the value of the two values is compared which is whichever is +1. And the second algorithm, first should understand the function of the ISB function, it returns 0 for the empty tree, for the balance tree to return the depth of the tree, for the unbalanced tree returns-1. Understand the function of functions and then see the code is much more clear, as long as a function returned 1, the entire function will return-1. (The specific process as long as a careful look at the understanding)

For recursion, the best way to understand it is to understand it from the functional meaning of the function. Understand how a problem is broken down into its sub-problems, so that the recursive function code is understood. Here is a misunderstanding (I have been in it), is through the analysis of the stack, a function of the call process, output results to analyze the recursive algorithm. This is very undesirable, this will only stun themselves, in fact, the recursive nature is also a function of the call, the function of the call is itself or not the fact that there is no difference. Some temporary information is always saved to the stack when the function is called, and the stack is just for the function to return correctly, that's all. As long as we know that recursion leads to a lot of function calls, a lot of stack operations are possible.

Summary

The basic idea of recursion is to transform large-scale problems into small-scale similar sub-problems to solve. When a function is implemented, because the method of solving the big problem and the method of solving the small problem are often the same method, it produces the case that the function calls itself. In addition, the problem-solving function must have an obvious end condition, so that no infinite recursion can occur.

Reproduced from the random talk recursion: the thought of recursion

A ramble on recursion: the thought of recursion--reprint

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.