32 Recursion

/ *
* Demand: factorial of 5
* 5 * 5 = 4 * 3 * 2 * 1; 120 //!
* 4 5 * 5 = 120 !; //!
* 4 4 * 3 = 24 !; //!
! 3 * 2 * 3 = 6 !; //
* 2 * 1 = 2 2 !; //!
* 1 = 1;! // 1


n! = n * (n - 1)!

Recursive: the big issue is split into many small problems, small problems and then split into more small problem,
when we put more small problems to solve, but also solve the small problems
with solving small problems, big problems with it solves the
continuous method call itself its own method

Recursion Note:
recursion must be exported , memory overflow
recursive number should not be too much , memory overflow

public void show(int n) {//5
//出口
if(n == 0) {
return;
}

show(n - 1);
}
*/

 

public class jiecheng {
    public static void main(String[] args) {
        int result = jiec(5);
        System.out.println(result);
    }

    public static int jiec(int n) {
        if(n==1) {
            return 1;//出口
        }else {
            return n * jiec(n-1); //n!=n*(n-1)!
        }
    }
}

Export

 

 

/ *
* Classical problem: a pair of rabbits from the first 3 months after birth were born one pair of rabbits each month,
* bunnies grow up to the third month after the month gave birth to one pair of rabbits, if the rabbit is not dead ,
* ask for the second ten months of rabbit number is how much?
*
*
* 1
* 1
* 2
* 3
* 5
* 8
* 13
*
* law: In addition to the first month and the second month, and the remaining two months before the month is the sum
* Fibonacci number of columns
*
* /

public class Demo2 {
    public static void main(String[] args) {
        int result = method(20);
        System.out.println(result);
    }

    //兔子数量多少对
    public static int method(int n) {
     if(n==1) {
         return 1;
     }else if (n==2) {
         return 1;
     }else {
         return method(n-1) + method(n-2); //If not the first and second months, the number of rabbits is the sum of the previous two months 
     } 
    } 
}

Export

 

Guess you like

Origin www.cnblogs.com/longesang/p/11304575.html