递归:方法定义中调用方法本身的现象(自己调自己)
public void show(int n){
if(n <= 0){
System.exit(0);
}
System.out.println(n);
show(--n);
}
注意3个事项: A:递归一定要有出口,否则就是死递归 B:递归的次数不能太多,否则就会内存溢出 C:构造方法不能递归使用
举例: 从前有座山,山里有座庙,庙里有个老和尚对小和尚说...... 庙挂了,或者山崩了
注意和方法的嵌套调用区别:
Math.max(Math.max(a,b),c);
需求:请用代码实现求5的阶乘
下面的知识要知道: 5! = 12345 5! = 5*4!
有2种方案实现: A:循环实现 B:递归实现 a:做递归要写一个方法 b:出口条件 c:规律
//循环实现
int jc = 1;
for(int x=2;x<=5;x++){
jc *= x;
}
System.jout.println("5的阶乘是:"+jc);
递归解决问题的思想
分解法、合并法
代码实现:
package com.linbin.time.se;
/**
* @author linbin
* @create 2019-05-11 18:11
*/
public class Digui {
public static void main(String[] args) {
System.out.println("5的阶乘是:"+jieCheng(5));
}
/**
* 做递归要写一个方法:
* 返回值类型:int
* 参数列表:int n
* 出口条件:
* if(n==1) {return 1};
* 规律:
* if(n!=1) {return n*方法名(n-1);}
* 方法名(n) -->n的阶乘
* 方法名(n-1) -->n-1的阶乘
*/
public static int jieCheng(int n){
if(n==1){
return 1;
}else{
return n*jieCheng(n-1);
}
}
}