递归知识

来源:互联网 发布:网络文字录入员 编辑:程序博客网 时间:2024/06/07 06:18

递归:

在递归算法执行过程中,计算机系统必定会用到的数据结构是栈;

栈的特点后进先出,再想想递归调用方法。最后调用的那次先出来,然后逐个出来;

递归的过程,利用栈保存现场地址,然后将数据入栈,运算,后出栈,返回结果

EX1:

intf(intn) {

    if(n<=3) return1;
    elsereturn f(n-2)+f(n-6)+1;
}
试问计算f(f(9))时需要计算(12)次f函数

EX2:

classprogram
 {
     staticvoid Main(string[] args)
     {
         inti;
         i = x(x(8));
     }
     staticint x(intn)
     {
         if(n <= 3)
             return1;
         else
             returnx(n - 2) + x(n - 4) + 1;
     }
 }
递归算法x(x(8))需要调用几次函数x(int n)?-----18


EX3:

int f(int x) {
    if(x <= 2)
        return1;
    returnf(x - 2) + f(x - 4) + 1;
}
How many times is f() called when calculating f(10)?------15




原创粉丝点击