饭来 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 seatunnel-web使用SQL组件时候后台报错,无法找到表格
  • ¥15 fpga自动售货机数码管(相关搜索:数字时钟)
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?