Some simple ideas about Recursion

Source: Internet
Author: User

My main blog: half an acre of fangtang

Recursion is an idea we use in programming. When a function calls itself directly or indirectly, it belongs to recursion, next, I will discuss some of my initial ideas about how to use recursion and how to use recursion.

  1. When to use recursion
    When the problem we want to solve involves repeated basic operations, we can consider using recursion.
  2. Several points of attention should be paid when programming with recursive thinking
    The first is the upper limit of recursion. It is usually an object that points out the effective range of the start position of recursion, which is generally used as a parameter for the main function transmission. The second is the lower limit of recursion, which is mainly used to determine the end of recursive operations, there must be a symbolic operation to exit recursion. Otherwise, recursion will continue indefinitely. Finally, it is to determine the basic operation to implement recursion and the change process from the upper limit of recursion to the lower limit of recursion, the basic operation has been taken into consideration when determining the use of recursion. It is important to consider the change process from the upper limit of recursion to the lower limit of recursion, which is prone to errors.

    The following two examples are used to deepen the understanding of the above section (C ++ implementation ):

    (1) Calculate the factorial of a number

    First, can recursion be used? When we calculate a factorial of a number, repetition involves the multiplication of two numbers. This is a basic operation for repeated execution. Therefore, we can use recursion to solve this problem. Secondly, what is the upper limit of recursion? Because the factorial implements the multiplication of all numbers from 1 to this number, the upper limit of recursion is the number itself. We can also get that the lower limit of recursion is 1, and finally, you need to determine the change process from the upper limit of recursion to the lower limit of recursion. Obviously, this change process is a process in which the number itself (the upper limit of recursion) is continuously reduced by 1 to 1 (the lower limit of recursion, that is, the process that the parameters transmitted by the main function are continuously reduced by 1. After the above analysis, the following code can be easily written:

    # Include
       
        
    Using std: cin; using std: cout; using std: endl; // Recursive Function for factorial operations int factorial (int val) {if (val> 1) return factorial (val-1) * val; // val-1 keeps the upper limit of recursion close to the lower limit of else. // In fact, else can also be left empty. Why? Return 1;} int main () {int ival = 0; cout <"Number of input factorial required:"; cin> ival; int res = factorial (ival ); cout <ival <"! Equal to "<res <endl; return 0 ;}
       

    For the above Code, else can not write the recursive function that implements the factorial operation, because when the parameter passed to factorial is equal to 1, the function returns 1 and ends recursion, the second-to-last factorial function is executed.return factorial(val - 1) * valAnd ends the second-to-last function call.return 1The call of other layers is the same. Therefore, the program is also correct without else. Here we write else to make the logic structure of the program clearer. In addition,return factorial(val - 1) * valInval - 1Do not change--valIf you change--valIf the parameter val is passed to the next factorial, the parameter val is changed along with the val of the current layer, which will undoubtedly cause errors.

    (2) output the content of the vector object

    First, can we use recursion? To continuously output the content of a vector object, this is a basic operation for repeated execution. Therefore, we can implement it using recursion. What is the upper limit of recursion? Some people say that it is the pointer to the element after the end of the vector object. But is it true? This is not correct. The pointer to the last element does not point to an object in a valid range. The bucket storage value it points to is undefined. Pay special attention to this, the true recursive upper limit should be the pointer minus 1 after the end of the vector object, which is the object within the valid range. Obviously, the lower limit of recursion is the pointer to the first element of the vector object. Finally, the process from the upper limit of recursion to the lower limit of recursion is that the upper limit of recursion is continuously reduced by 1 to approach the lower limit of recursion until the value is equal to the lower limit of recursion. The following code is also easily written:

    # Include
       
        
    # Include
        
         
    Using std: cin; using std: cout; using std: endl; using std: vector; // implement the recursive function void print (const vector
         
          
    & Vec, decltype (vec. begin () ibeg, decltype (vec. begin () iend) {if (iend! = Ibeg) print (vec, ibeg, iend-1); // iend-1 makes the upper limit of recursion keep approaching the lower limit of cout <* iend <""; // before this, else} int main () {vector cannot exist.
          
           
    Ivec; int ival; cout <"Enter the 10 integers in the vector object in sequence:" <endl; for (unsigned I = 0; I! = 10; ++ I) {cin> ival; ivec. push_back (ival);} // print the 10 numbers print (ivec, ivec. begin (), ivec. end ()-1); // The true upper limit of recursion should be the pointer minus 1 cout after the end of the vector object <endl; return 0 ;}
          
         
        
       

    Similarly, in implementing recursive functions that print vector object Elementsiend - 1Cannot be changed--iendBecause this will change the value of the iend parameter in the current layer function, and the expected results will not be obtained. The type of the vector object in the form parameter is the reference type, this avoids the low time efficiency and the waste of storage space caused by copying. At the same time, the use of const only outputs elements because it does not need to change the value of elements.

    The above are some of my simple ideas on the use of recursive ideas. With more in-depth understanding, I will post relevant blog posts. You are welcome to provide valuable comments.


Related Article

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.