Learn to understand the difference between recursion and tail recursion

Source: Internet
Author: User

After learning recursion and tail recursion, I have done some simple summary, easy to learn.

Take the typical Fibonacci sequence as an example and compare the two:

ImportJava.util.Scanner; Public classTestfibonacci { Public Static voidMain (string[] args) {Scanner sc=NewScanner (system.in); intn =Sc.nextint ();        System.out.println (FIBONACCI1 (n)); System.out.println (Fibonacci2 (N,The));    FIBONACCI3 (n); }        //Non-tailed recursion     Public Static LongFIBONACCI1 (intN) {        if(n==1)            return1; Else if(n==2)            return1; Else             returnFIBONACCI1 (n-1) +fibonacci1 (n-2); }        //Tail recursion     Public Static LongFibonacci2 (intNintF1,intF2) {        if(n==1)            returnF1; Else             returnFibonacci2 (n-1,f2,f1+F2); }        //Iterative Method     Public Static voidFibonacci3 (intN) {        intF1 = 1,f2 =1, F;  for(inti=3;i<=n;i++) {f=F2; F2= F1 +F2; F1=F;    } System.out.println (F2); }    }

Recursion is a good way to solve the problem, but sometimes it is limited by memory, which results in very slow operation, long result, and a lot of repeated computation, resulting in waste. In contrast, the iterative memory requirements are much less, because the iteration is the result of each step of the operation to participate in the next operation, does not produce too many duplicate calculations, so the calculation is very fast, but the iterative mode of thinking is not easy to figure out, need to replace the intermediate number. and the tail recursion, I think it is a new algorithm between the two, in the recursion to apply the idea of iteration, the results of each step as a parameter return, participate in the next recursive operation, until the condition terminates.

Learn to understand the difference between recursion and tail recursion

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.