【数据结构与算法分析】2.1 斐波拉切数列算法实现

问题描述:

有形如 1,1,2,3,5,8,13,21,34...的数列,从第三项开始的结果为前两项之和,称作斐波拉切数列,即f(0) =0,f(1) =1;f(n) = f(n-1) + F(n-2);

解决思路:

1.采用递归的方式,从上而下计算,优点是理解简单,缺点是复杂度太高,呈指数增长

2.方法一是因为重复计算了,比如要算f(4)需先求出f(3)和f(2),要算f(3)要先求出f(2)和f(1),这里f(2)被计算了两次了,n越大,重复的越多,好的方法是重复的就不计算了

3.方法2的复杂度已经为O(n),但是使用的递归,n太多会造成堆栈溢出,所以采用从下而上的递推更好

4.最好的是数学公式,这个自己去查了。。。。。。

算法实现:

#include
#include
#include"time.h"
long long int fibonacciOfRecursion(int n);
long long int fibonacciOfCutBranches(int n);
long long int fibonacciOfRecurrence(int n);
long long int result[10000] = {0};
int main() {
    int n;
    clock_t start1,finish1,start2,finish2,start3,finish3;
    while(scanf("%d",&n)!=EOF){
            start1 = clock();
            long long int answer = fibonacciOfRecursion(n);
            finish1 = clock();
            double  duration = (double)(finish1 - start1)/CLOCKS_PER_SEC;
            start2 = clock();
            long long int answer2 = fibonacciOfCutBranches(n);
            finish2 = clock();
            double  duration2 = (double)(finish2 - start2)/CLOCKS_PER_SEC;
            start3 = clock();
            long long int answer3 = fibonacciOfRecurrence(n);
            finish3 = clock();
            double  duration3 = (double)(finish3 - start3)/CLOCKS_PER_SEC;
            printf("The  recursion  costs %lf seconds,and the answer is %d\n",duration,answer);
            printf("The  cutBranches  costs %lf seconds,and the answer2 is %d\n",duration2,answer2);
            printf("The  recurrence  costs %lf seconds,and the answer3 is %d\n",duration3,answer3);
    }
    return 0;
}  
long long int fibonacciOfRecursion(int n) {
    if(n<=1)
        return (n == 1 ? 1 : 0);
    else
        return fibonacciOfRecursion(n-1) + fibonacciOfRecursion(n-2);
}
long long int fibonacciOfCutBranches(int n) {
    if(n<=1)
        return (n == 1 ? 1 : 0);
    else if(result[n]  != 0)
        return result[n];
    else {
        result[n] = fibonacciOfCutBranches(n-1) + fibonacciOfCutBranches(n-2);
        return result[n];
    }
}
long long int fibonacciOfRecurrence(int n) {
    long long int first = 0;
    long long int second = 1;
    long long int fn = 0;
    if (n<=1)
        return (n == 1 ? 1:0);
    int i;
    for (i=2;i<=n;i++){
        fn = first + second;
        first = second;
        second = fn;
    }
    return fn;
}
【数据结构与算法分析】2.1 斐波拉切数列算法实现_第1张图片

你可能感兴趣的:(数据结构与算法)