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