递归函数的Big Theta(Θ)运行时

Big Theta (Θ) runtime of recursive functions

本文关键字:运行时 Theta Big 递归函数      更新时间:2023-10-16

我在理解运行时遇到了问题。任何帮助都将不胜感激!

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;
 }