#include <iostream>using namespacestd;/*Recursive method*//*recursive method calls itself in the function, notice the end condition, avoid infinite loop, the principle of recursion is to stack out the stack*//*example 1:f (n) =n! f (n) =f (n-1) *n*/intF1 (intN) { if(N <2)return 1; Else returnN*F1 (N-1);}/*Example 2 staircase has n steps, upstairs can step up to 1 steps, can also step up to 2 order, compiling a program to calculate the total number of different methods.*//*Analysis: The final step can take one step from the n-1 steps, can walk from the N-2J step 2 steps, f (n) =f (n-1) +f (n-2), F (1) =1,f (2) =2 similar to the previous Fibonacci sequence*/intF2 (intN) { if(1==n | |2==n)returnN; Else returnF2 (N-1) + F2 (N-2);}intMain () {intN; cout<<"Example 1:n="<<Endl; CIN>>N; cout<<"F1 (n) ="<<F1 (n) <<Endl; cout<<"Example 2:n="<<Endl; CIN>>N; cout<<"F2 (n) ="<<F2 (n); return 0;}
Three recursive methods based on algorithm