该函数的第一次递归调用会是什么样子?
int Fun(int m, int n)
{
if(n==0)
{
return n + 2;
}
return Fun(n-1, m-1) + Fun(m-1,n-1) + 1;
}
对于此功能,我完全失去了第一种情况的外观。我不明白为什么该函数有两个参数,以及为什么我们只在基本情况下返回1个参数。解决这个问题的过程是什么?您想向我解释的任何输入都很好(3,3)。虽然,现在我在考虑一个功能,如果其中一个输入比另一个输入小(3,2)或(2,3)会怎样?
int Fun(int m, int n)
{
if(n==0)
{
return n + 2;
}
return Fun(n-1, m-1) + Fun(m-1,n-1) + 1;
}
I'm completely lost as to what the 1st case would visually look like for this function. I don't understand why the function has two parameters and why we only return 1 parameter at the end with our base case. What would be the process to work this out? Any input you want to use to explain to me is fine I was trying (3,3). Although, now that I'm thinking about it how would this function look like if one of the inputs was smaller than the other like (3,2) or (2,3)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请注意,
返回n + 2;
简化为返回2;
。该函数需要两个参数(参数)并返回一个值。这就像添加您在学校第一年所学的两个数字的操作一样。
是否
fun(n -1,m -1)
在fun(m -1,n -1)
之前均未由C ++标准指定。因此,我无法告诉您第一个递归电话会是什么样。这使编译器在做出优化选择方面具有更大的自由度。当然,称为功能的顺序对最终结果没有影响。分析特定情况下发生的情况的最佳方法是使用线路调试器使用一条线。
Note that
return n + 2;
simplifies toreturn 2;
.The function takes two arguments (parameters) and returns a single value. That's like the operation of adding two numbers that you were taught in your first year at school.
Whether or not
Fun(n - 1, m - 1)
is called beforeFun(m - 1, n - 1)
is not specified by the C++ standard. So I can't tell you what the first recursive call will look like. This gives compilers more freedom in making optimisation choices. Of course the order in which the functions are called has no effect on the eventual result.The best way of analysing what happens in your particular case is to use a line by line debugger.
递归功能没有什么特别的 - 它们的工作原理完全像非恢复功能。
fun(3,3)
做到这一点:它需要
fun(2,2)
的值,这需要
fun(1,1 )
,doand and
fun(0,0)
确实返回2,因为条件是正确的。
因此,
fun(1,1)
将做5,而
fun(2,2)
将做11,
fun(3,3 )
将做23。
我敢肯定,您可以自己处理其他示例。
There is nothing special about recursive functions - they work exactly like non-recursive functions.
Fun(3,3)
does this:It needs the value of
Fun(2,2)
, which does this:And that needs
Fun(1,1)
, which doesand
Fun(0,0)
doeswhich returns 2 since the condition is true.
So,
Fun(1, 1)
will dowhich is 5, and
Fun(2,2)
will dowhich is 11, and
Fun(3,3)
will dowhich is 23.
I'm sure you can work through other examples on your own.