7.斐波那契数列——剑指offer

题目描述

大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项(从0开始,第0项为0)。

n<=39

//递归,大量重复计算
class Solution {
public:
    int Fibonacci(int n) {
     if(n == 0) return 0;
        if(n == 1) return 1;else return Fibonacci(n - 1) + Fibonacci(n - 2);
    }
};
//动态规划
class Solution {
public:
    int Fibonacci(int n) {
        int f = 0, g = 1;
        while(n--) {
            g += f;
            f = g - f;
        }
        return f;
    }
};

 

posted @ 2019-05-11 22:53  unique_ptr  阅读(70)  评论(0编辑  收藏  举报