【问题标题】:Big Theta (Θ) runtime of recursive functions递归函数的 Big Theta (Θ) 运行时
【发布时间】:2015-12-12 05:08:35
【问题描述】:

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

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 和 bar 的基本情况需要 2.T(0) = 2 = Θ(1)。但我不明白如何为递归函数制定递归关系。
  • 插入数字和纸迹?

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


【解决方案1】:

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

Bar 也在做同样的事情,没有打印,只是递减和调用 foo

是3级递归,尽量用小数,顺其自然,比如4

-Bar 得到 4,case base 是 0,4 大于 0 所以它会继续,它会调用 foo(4) (记住 foo 是一个递归调用,会打印 4 到 0 => 43210,每次减1) - 再次调用 bar,这次 n-1 = 4 -1 = 3,值为 3,它将调用 foo(3) 和相同

当你遇到 bar, n == 0 的 case base 时,你将停止调用其他函数,这个函数会得到返回值,你可以在 screnn 上打印,但这并不意味着函数结束,它正在等待要返回的其他值,当它返回时,它会打印调用它的 n,因此它将是 1234,也就是说,值 1、2、3 和 4 是一次输入一个柱的值,并打印foo (for 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;
 }

【讨论】:

  • 非常感谢!我现在对程序的理解好多了:) 那么,大 theta 运行时是 i=0 到 i 的 n 的总和吗? Θ(n^2)?有没有更好的方法来考虑运行时?
  • 我认为它是 n+n² 但我不完全确定,所以我没有发布任何关于它的信息
猜你喜欢
  • 1970-01-01
  • 2022-08-18
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多