动态规划--1-斐波那切数列

 

题目

        大家都知道斐波那契数列,现在要求输入一个整数n,请你输出斐波那契数列的第n项。(n<=39)

问题:

        我们不难发现在这棵树中有很多结点是重复的,而且重复的结点数会随着n的增加而急剧增加,这意味计算量会随着n的增加而急剧增大。

一:一般循环

class Solution {
public:
    int Fibonacci(int n) {
        if(n <= 1)
            return n;
        int first = 0, second = 1, third = 0;
        for (int i = 2; i <= n; i++) {
            third = first + second;
            first = second;
            second = third;
        }
        return third;
    }
};

二:动态规划

class Solution 
{
public:
    int Fibonacci(int n) 
    {
     if (n <= 1)
        return n;
    if (memo[n]) return memo[n];
    else
        return memo[n] = Fibonacci(n-1) + Fibonacci(n-2);
    }
private:
    int memo[40];        // 全局变量,初始化为0
};

 

你可能感兴趣的:(----------动态规划,剑指offer)