zoukankan      html  css  js  c++  java
  • 关于递归次数的计算

    有这样一个题目:

    递归函数:

     1 int x(int n)
     2 {
     3     if(n<=3)
     4     {
     5         return 1;
     6     }
     7     else
     8     {
     9         return x(n-2)+x(n-4)+1;
    10     }
    11 }

    计算x(x(8))递归调用次数。

    大多数可能觉得这是一个很简单的题目,的确很简单。

    但是要想在没有编译器的情况下正确的算出这个递归

    调用次数其实还是需要点耐心.

    x(x(8))我们先计算x(8),我们用count=0计数递归调用次数

    1.x(8)=x(6)+x(4)+1 count=1;

    2.x(6)=x(4)+x(2)+1,x(4)=x(2)+x(0)+1  x(8)=x(4)+2*x(2)+x(0)+3 count=3;

    3.x(4)=x(2)+x(0)+1 x(8)=3*x(2)+2*x(0)+4  count=4

    4.x(2)=1,x(0)=1; x(8)=9 count=9

    再计算x(9)

    1.x(9)=x(7)+x(5)+1 count=10

    2.x(7)=x(5)+x(3)+1,x(5)=x(3)+x(1)+1  x(9)=x(5)+2*x(3)+x(1)+3 count=12

    3.x(5)=x(3)+x(1)+1 x(9)=3*x(3)+2*x(1)+4 count=13

    4.x(3)=1 x(1)=1   x(9)=3+2+4=9 count=18

    接下来我们再用程序验证一下:

     1 #include <iostream>
     2 using namespace std;
     3 
     4 static int count=0;
     5 
     6 int x(int n)
     7 {
     8     if(n<=3)
     9     {
    10         count++;
    11         return 1;
    12     }
    13     else
    14     {
    15         count++;
    16         return x(n-2)+x(n-4)+1;
    17     }
    18 }
    19 
    20 int main(void)
    21 { 
    22     cout<<"x(x8)="<<x(x(8))<<endl;
    23     cout<<"count="<<count<<endl;
    24     system("pause");
    25     return 0;
    26 }

    运行截图:

    验证正确了

    对于这种计算递归调用次数一定要思路清晰,最好是将所有的递归调用都递归到递归出口的

    地方再统一进行递归出口的调用,这样不容易造成紊乱,个人意见,仅供参考。

  • 相关阅读:
    install kde in ubuntu
    Upgrade to or Install Cinnamon 2.4 in Ubuntu
    enjoy dollar vs cash dollar
    opencv linux
    高频交易都有哪些著名的算法
    wpf
    opencv mat flags含义
    gphoto2 canon eos450d
    gphoto2
    task optimization之superglue分析
  • 原文地址:https://www.cnblogs.com/vpoet/p/4769789.html
Copyright © 2011-2022 走看看