当前位置:网站首页>recursion: method calls itself
recursion: method calls itself
2022-08-01 23:37:00 【XLMN】
public class Study05 {
public static void main(String[] args) {/*** recursion: the method calls itself** /** *1. What is recursion?* * is the method itself calling itself.*** *2.f(int n);*** *f(int n){* * f(n-1);//Direct call;* *}*** *f(int n){* * a(n);//Indirect call;* *}*** *a(int n){* * f(n-1);* *}*** *3. Calculate 5!* *5!=5*4!* *4!=4*3!* *3!=3*2!* *2!=2*1!* *1!=1;*** *public static int factorial(int n){*** * int result=n*factorial(n-1);*** * return result;* *}*** *4. Two elements of recursion:* * 1) Rules for method invocation itself;* * 2) The end condition of the recursion; if there is no end condition, there will be a stack overflow, java.lang.StackOverflowError.* *5. Advantages and disadvantages of recursion:* * 1) The idea is simple;* * 2) Every time a method is called, the stack memory is opened up; the memory consumption is large, which affects the performance; if the performance requirements are high, avoid using recursion.* *6. Features of recursion:* * 1) A problem can be decomposed into several sub-problems with the same level;* * 2) The solution of the outer layer problem depends on the solution of the inner layer problem;* * 3) The solution to the problem of each layer is consistent;* * 4) There must be an end condition.* * 5) Recursive problems can be solved with loops.*/System.out.println(sum(4));}//Use recursive method to find factorialpublic static int sum(int a) {int temp = 0;if (a == 1) {temp = 1;//End condition} else {temp = a * sum(a - 1);}return temp;}
}
边栏推荐
- Additional Features for Scripting
- 避免使用 <b>、<i>、<s> 和 <u> 标签
- Calculate the midpoint between two points
- 递归:方法调用自身
- When using DocumentFragments add a large number of elements
- Secondary Vocational Network Security Competition B7 Competition Deployment Process
- [Camp Experience Post] 2022 Cybersecurity Summer Camp
- npm npm
- ICLR 2022最佳论文:基于对比消歧的偏标签学习
- Nacos配置中心之加载配置
猜你喜欢
随机推荐
Access the selected node in the console
nodejs--process
YOLO等目标检测模型的非极大值抑制NMS和评价指标(Acc, Precision, Recall, AP, mAP, RoI)、YOLOv5中[email protected]与
基于JAX的激活函数、softmax函数和交叉熵函数
6133. 分组的最大数量
numpy.where
[Recommended books] The first self-driving technology book
毕业作业
Jmeter是什么
LocalDateTime转为Date类型
ELK log collection
[LeetCode304周赛] 两道关于基环树的题 6134. 找到离给定两个节点最近的节点,6135. 图中的最长环
From 0 to 100: Notes on the Development of Enrollment Registration Mini Programs
邻接表与邻接矩阵
递归:方法调用自身
Check if point is inside rectangle
An interview question about iota in golang
The third chapter of the imitation cattle network project: develop the core functions of the community (detailed steps and ideas)
企业防护墙管理,有什么防火墙管理工具?
6134. 找到离给定两个节点最近的节点-力扣双百代码