First, the recursive function, the popular saying is that the function itself calls itself ...
such as: N!=n (n-1)!
You define the function f (n) =nf (n-1)
and f (n-1) is the function of this definition. This is recursion.
Second, why use recursion: The purpose of recursion is to simplify the programming, make the program easy to read
Third, the drawback of recursion: although the non-recursive function of high efficiency, but more difficult to program, poor readability. The drawback of recursive functions is that the overhead is added, that is, the stack memory takes up a little more per recursive
Iv. conditions of recursion: statements that require completion of a task, need to meet the requirements of recursion (decrease rather than divergence)
V. Advanced recursion:
1. Use recursion to calculate the factorial of N:
Analysis: n!=n* (n-1) * (n-2) ... *
public int Dreturn (int n) {
if (n==1) {
return 1;
}else{
Return N*dreturn (n-1);
}
}
2. Use the recursive function to calculate the sum of 1 to N: 1+2+3+4+. +n
public int Dreturn (int n) {
if (n==1) {
return 1;
}else{
Return N+dreturn (n-1);
}
}
3. Require output a sequence: 1,1,2,3,5,8,11 ... (the sum of the first two digits of each number, requiring a recursive function)
A function is represented by the return of Java: F (n) =f (n-1) +f (n-2); F (0) = 1; F (1) = 1;
Analysis: x1=1; X2=1; x3=x1+x2; x4=x2+x3; ... ; Xn=x (n-1) +x (n-2)
public int F (int n) {
if (n==1) {
return 1;
}else if (n==2) {
return 1;
}else{
Return F (n-1) +f (n-2);
}
}
4.java reverse printing of individual elements in an integer array using a recursive method
public static void printall (int index,int[] arr) {
System.out.println (Arr[index]);
if (Index > 0) {
Printall (--index,arr);
}
}
public static void Main (string[] args) {
Int[] arr={1,2,3,4,5};
Printall (Arr.lenth-1,arr);
}
5. Programming Solution: If a heifer, starting from the birth of the fourth year start a cow, according to the law, how many cows in the nth years?
public static int cattle (int n) {
if (n<=0) {
return 0;
}else if (n<=3) {
return 1;
}else{
Return cattle (n-1) +cattle (n-3);
}
}
public static void Main (string[] args) {
int n=10;
System.out.println (n+ "years later jointly owned" +cattle (n) + "cattle");
}
The concept of recursion, linear recursion, and tail recursion?
Java Recursive functions