Java:递归问题

递归概述

递归是方法中调用方法本身的这种现象
注意事项:
1.要有出口,如果没有出口,就是死递归
2.递归次数不能太多
如果出现这两种情况,栈内存会因为加载过多的方法而造成栈溢出
递归是一种拆分合并的思想
将大的问题拆分成小的问题,通过解决小的问题来解决大的问题
练习:

//求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
*/
不死神兔问题
/*
有一对兔子,从出生后第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);
}
//兔子的对数所组成的数列被称为斐波那契数列
切饼问题
/*
饼不许离开砧板,求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);
}
发布了26 篇原创文章 · 获赞 1 · 访问量 372

猜你喜欢

转载自blog.csdn.net/weixin_45919908/article/details/103448194