366 斐波那契数列

原题网址:https://www.lintcode.com/problem/fibonacci/description

描述

查找斐波纳契数列中第 N 个数。

所谓的斐波纳契数列是指:

  • 前2个数是 0 和 1 。
  • 第 i 个数是第 i-1 个数和第i-2 个数的和。

斐波纳契数列的前10个数字是:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ...

The Nth fibonacci number won't exceed the max value of signed 32-bit integer in the test cases.

您在真实的面试中是否遇到过这个题?  

样例

给定 1,返回 0

给定 2,返回 1

给定 10,返回 34

标签
枚举法
非递归
数学

AC代码:

class Solution{
public:
    /**
     * @param n: an integer
     * @return an integer f(n)
     */
    int fibonacci(int n) {
        // write your code here
int *p=new int[n];
if(n==1)
{    p[0]=0; return p[0];}
else if(n==2)
{p[1]=1; return p[1];}
else
{
p[0]=0;
p[1]=1;
for(int i=3;i<=n;i++)
p[i-1]=p[i-2]+p[i-3];
return p[n-1];
}
    }
};

猜你喜欢

转载自www.cnblogs.com/Tang-tangt/p/9253824.html
今日推荐