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

时间:2015-12-12 05:08:36

标签: c++ recursion big-o time-complexity big-theta

我在尝试理解运行时遇到了麻烦。任何帮助将不胜感激!

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

1 个答案:

答案 0 :(得分:0)

Foo正在打印您传递的数字,它将执行x--直到为0,如果您传递5将打印543210,因此您可以将其称为n减1并打印结果

Bar正在做同样的事情而不打印,只是递减并调用foo

这是一个3递归级别,尝试使用一个小数字并按照流程,如4

-Bar得到4,大小写为0,4大于0所以它会继续,它会调用foo(4)(请记住,foo是一个递归调用,将打印4到0 =&gt; 43210 ,每次递减1) - 再次调用条形图,这次使用n-1 = 4 -1 = 3,值为3,它将调用foo(3)并且相同

当您在bar中遇到案例库时,n == 0您将停止调用其他函数并且此函数将获得返回的值,您可以在screnn上打印但它并不意味着函数结束,它正在等待要返回的其他值,当它返回时会打印出调用它的n,因此它将是1234,即值1,2,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;
 }