递归函数的Big Theta(Θ)运行时
Big Theta (Θ) runtime of recursive functions
我在理解运行时遇到了问题。任何帮助都将不胜感激!
int foo(int x) {
if (x <= 0) return x;
cout << x;
return foo (x-1);
}
void bar(int n) {
if (n <= 0) return;
cout << foo (n) << endl;
bar (n-1);
cout << n;
}
int main() {
int n;
cin >> n;
bar(n);
return 0;
}
Foo正在打印您传递的数字,它将执行x——直到为0,如果您传递5,它将打印543210,因此您可以将其称为递减n乘以1,并打印结果
Bar在不打印的情况下也在做同样的事情,只是递减并调用foo
它是一个3递归级别,尝试使用一个小数字并遵循流程,如4
-Bar得到4,大小写为0,4大于0,因此它将继续,它将调用foo(4)(记住foo是一个递归调用,它将打印4到0=>43210,每次将数字递减1)-bar再次被调用,这次n-1=4-1=3,值为3,它将调用foo(3)和相同的
当你在bar中遇到case base时,n=0,你将停止调用其他函数,这个函数将得到返回的值,你可以在screnn上打印,但这并不意味着函数结束,它正在等待其他值返回,当它返回时,它打印调用它的n,所以它将是1234,也就是说,3和4是一次输入一个条形图的值,并打印foo的结果值(对于4,3,2,1),因为这是您得到的
int foo(int x) { //Decrementing by one and printing the value
// If x reaches 0 exit (you need an exit in a recursion)
if (x <= 0) return x;
// Print the value x (the first time x will be the n, the second n-1)
cout << x;
// Call the same function in we are but with x-1 value
return foo (x-1);
}
// It will produce foo(4)=>foo(3)=>foo(2)=>foo(1) and foo(0)
// foo(0) will break the recursion and finish here (only prints)
// It is where main calls and enters n is the value you type
void bar(int n) {
// Case base to break recursion when it reaches 0
if (n <= 0) return;
// Here is the code that prints the line that foo will make
cout << foo (n) << endl;
// Here you will call the same function but with n-1, like foo does
bar (n-1);
// When all the recursion above is over you will get here
// In the stack you will have done n calls into here with n-x
// So every one will print the value of n that in the paremeter
// when the call was make
cout << n;
}
相关文章:
- CMake-按正确顺序将项目与C运行时对象文件链接
- 我在c++代码中生成了一个运行时#3异常
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 删除指向指针的指针是运行时错误吗
- 如何用参数值调用函数(仅在运行时已知)
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- c++中的指针和运行时错误
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- 有没有一种方法可以测量c++程序的运行时内存使用情况
- 建议在运行时将带有类实例的列表从c++导入qml
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 如何在GTK程序运行时禁用屏幕保护程序/电源管理/屏幕消隐
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 读取文件时运行时的未知行为
- 函数在Windows或Linux上运行时表现不同
- 在声明中合并两个常量"std::set"(不是在运行时)
- AWS Lambda C++运行时权限被拒绝
- 2 个对数嵌套循环的 Theta 运行时
- 递归函数的Big Theta(Θ)运行时