我最近开始研究算法和数据结构。我遇到了斐波那契问题及其使用递归的解决方案。但事实就是如此。我理解递归调用如何只有一个(如数字的阶乘)。函数调用继续堆叠,直到它们达到基本情况,然后他们开始解开一个到期望的答案。
但是我没有得到的是当f(n)+ f(n / 2)这样的表达式中有两个递归调用时,递归是如何工作的。我的意思是首先解决哪个呼叫以及何时解决第二个呼叫。如果将此表达式分配给语句,如何计算总和? 我写了一个小代码来解读这个。
#include <iostream>
#include <string>
int main()
{
int recursionTest(int n, char c);
int x;
std::cin>>x;
std::cout<<"Ans:"<<recursionTest(x,'c');
}
int recursionTest(int n,char c)
{
int result=0;
if(n==0)
return 1;
std::cout<<n<<":"<<c<<std::endl;
result=recursionTest(n/2,'L')+recursionTest(n/3,'R');////I cant figure
out the flow of
control here!!!
return result;
}
我得到了以下输出。
24
24:c
12:L
6:L
3:L
1:L
1:R
2:R
1:L
4:R
2:L
1:L
1:R
8:R
4:L
2:L
1:L
1:R
2:R
1:L
Ans:20
我得到它,它是一个树形结构。但我仍然不知道我们如何得到20作为答案(输入= 24)。 sum表达式如何工作以及它的总和是什么,如何查看树结构并生成相同的输出?
答案 0 :(得分:2)
There is no defined order to how the two subexpressions of the +
operator are evaluated. The compiler can emit code to evaluate either one first and the other one second. It can even interleave some computations of one side with computations of the other. For example, it could calculate n/3
, then n/2
, then the right function call, and finally the left function call.
The flow control is just like for a single case of recursion followed by another single case. So, your line:
result=recursionTest(n/2,'L')+recursionTest(n/3,'R');
is effectively the same as:
int left = recursionTest(n/2,'L');
int right = recursionTest(n/3,'R');
result = left + right;
except for the implication in my version that the left function call is guaranteed to be evaluated before the right function call.
答案 1 :(得分:-1)
Here operator precedence will play the role
f(n) + f(n/2);
In the above code snippet f(n) will get called first and then f(n/2). basically arithmetic operators compile from left to right. If you want to debug the code use printf statements inside function f(int) by printing n value . By this you can get the hang of the code