饭来 2019-04-04 10:41 采纳率: 100%
浏览 450
已采纳

关于用递归来计算斐波那契数组的问题

正常的方式我懂,不过老师让我们做一个更有效率的递归函数就不是很懂了,大概就是把之前计算出来的值储存起来,这样就不会再去运算计算过的值了。
下面是老师要求的原话:
1. Calculating Fibonacci Numbers
In mathematical terms, the sequence of Fibonacci numbers is defined by the recur-
rence relation Fn=Fn−1+Fn−2,where F0= 0 andF1= 1 .

First think about how to recursively determine the values of specific Fibonacci
numbers. You are required to construct a class called Fibonacci that reads in anumber n and outputs the n-th Fibonacci numberFn.

2.More Efficient Fibonacci Calculation

In order to calculate Fn, you need to recursively calculate Fn−1 and Fn-2. Then, to aclculateF n−1, we needFn−2(again!) andFn−3. This means that many Fibonaccinumbers may be calculated multiple times.Reproduce yourFibonacciclass in another class called EfficientFibonacci.
Make this class efficient by storing calculated numbers. The recursive function should not be called for a number that has already been calculated.

  • 写回答

1条回答 默认 最新

  • threenewbee 2019-04-04 11:08
    关注
    #include <stdio.h>
    
    int arr[1000];
    int top = 0;
    
    int Fibonacci(int n)
    {
    if (n <= 2 && top == 0)
    {
    top = 2;
    arr[0] = 1;
    arr[1] = 1;
    return arr[n - 1];
    }
    if (top == n - 1)
    {
    top = n;
    arr[n - 1] = arr[n - 2] + arr[n - 3];
    return arr[n - 1];
    }
    else if (top > n - 1)
    {
    return arr[n - 1];
    }
    return Fibonacci(n - 2) + Fibonacci(n - 3);
    }
    
    int main()
    {
        for (int i = 1; i <= 20; i++)
            printf("%d ", Fibonacci(i));
       return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制