Recursive Functions have a flow that goes like this
DoSomeWork
If work is done, return answer Otherwise, call myself and change the input
For example, let's say I have an integer from 0-100, and I want to reclusively check how many numbers from 100 my number is
public int DistanceFromLimit(int start,int steps){
if(start==100){
return steps;
}
else{
return DistanceFromLimit(start+1,steps+1);
}
public static void main(String[] args) {
DistanceFromLimit(75,0);
}
When my program starts, steps is 0 and start is 75. My program checks start and sees that 75 is not 100. So it then calls itself with start at 76 and steps at 1. The 2nd layer of the program sees that 76 is not 100, so it calls itself with start as 77 and steps at 2.
This will keep going until steps finally is 100.
So you need to provide work and a condition of when that work is done. If the work is done, return some answer. If the work is not done, then call the same function, changing the input to represent the work already done.
发布评论
评论(2)
诀窍是您可以在给出的接口之外创建其他方法:
}
The trick is that you can create additional methods outside of the interface you were given:
}
递归功能的流量如该
作品,
如果完成工作,请返回答案
否则,请打电话给自己并更改输入,
例如,我有一个从0-100起的整数,我想彻底检查100个数字的数量是我的数字,我的数字是
我的程序启动时,步骤为0,启动是75。程序检查开始并发现75不是100。因此,它随后以76的启动自称为76,并以1个步骤。该程序的第二层看到76不是100 。
这将继续进行,直到最终为
100
如果完成工作,请返回一些答案。如果没有完成工作,请调用相同的功能,更改输入以表示已经完成的工作。
Recursive Functions have a flow that goes like this
DoSomeWork
If work is done, return answer
Otherwise, call myself and change the input
For example, let's say I have an integer from 0-100, and I want to reclusively check how many numbers from 100 my number is
When my program starts, steps is 0 and start is 75. My program checks start and sees that 75 is not 100. So it then calls itself with start at 76 and steps at 1. The 2nd layer of the program sees that 76 is not 100, so it calls itself with start as 77 and steps at 2.
This will keep going until steps finally is 100.
So you need to provide work and a condition of when that work is done.
If the work is done, return some answer. If the work is not done, then call the same function, changing the input to represent the work already done.