Java: Recursion

Recursive Overview

This phenomenon is the recursive method calls the method itself
Notes:
1. have export, if no exit is death recursive
2. recursion can not be too much
if the two cases appear, stack memory because of excessive loading method the resulting stack overflow
recursion is a split merge ideas
will split the big problems into small problems to solve big problems by solving small problems
exercise:

//求5的阶乘
/*
5!-->4!*5
4!-->3!*4
3!-->2!*3
2!-->1!*2
1!=1
*/
public static void main(String[] args) 
{
    int result=calculateFactorial(5);
    System.out.println(result);
}
public static int calculateFactorial(int num)//计算阶乘
{
	if(num==1)
		return 1;
	else if
		return num*calculateFactorial(num-1);
}
/*
递归其实是一个找规律的过程,找到规律然后运用递归来计算
我们来分析一下求5!的过程
1.首先调用calculateFactorial方法,传入5
2.返回5*calculateFactorial(4)
3.方法内调用该方法calculateFactorial(4)返回4*calculateFactorial(3)
4.calculateFactorial(3)返回3*calculateFactorial(2)
5.calculateFactorial(2)返回2*calculateFactorial(1)
6.calculateFactorial(1)返回1
最后calculateFactorial(5)的结果是:5*4*3*2*1
*/
Death is not the rabbit problem
/*
有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,
假如兔子都不死,问第二十个月的兔子对数为多少?
月份	对数
 1		 1
 2		 1
 3		 2
 4		 3
 5		 5
 6		 8
 ......
 n-2     i
 n-1	 j
 n		 i+j
我们观察规律可得:第n月的兔子对数等于第n-2月的兔子对数加上第n-1月的兔子对数,第一个月和第二个月的兔子对数为1
*/
public static void main(String[] args) {
    int num=calRabbit(20);
    System.out.println(num);
}
public static int calRabbit(int month)//计算兔子对数,month代表月份
{
    if(month==1||month==2)
        return 1;
    else
        return calRabbit(month-1)+calRabbit(month-2);
}
//兔子的对数所组成的数列被称为斐波那契数列
A cake-cutting issues
/*
饼不许离开砧板,求n(1<=n<=100)刀最多能切成多少块。
第1刀---2块
第2刀---4(2+2)块
第3刀---7(3+4)块
第4刀---11(4+7)块
......
第(n-1)刀---i块
第n刀---(n+i)块
*/
public static void main(String[] args) {
   int num=cutCake(4);
    System.out.println(num);
}
public static int cutCake(int n)//计算饼的块数,n代表切的刀数
{
    if(n==1)
        return 2;
    else
        return n+cutCake(n-1);
}
Published 26 original articles · won praise 1 · views 372

Guess you like

Origin blog.csdn.net/weixin_45919908/article/details/103448194