7.斐波那契数列

来源:互联网 发布:淘宝面交交易被骗 报警 编辑:程序博客网 时间:2024/06/06 00:12
斐波那契数列
  • 参与人数:7827时间限制:1秒空间限制:32768K
  •  算法知识视频讲解

题目描述

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

这道题比较简单,递归效率太低,最好用迭代的方法做。

class Solution {public:    int Fibonacci(int n) {        if ( n == 0 )            return 0 ;                if ( n == 1 )            return 1 ;                int preTwo = 0 ;        int preOne = 1 ;        int result = 0 ;                for ( int i = 2; i <= n; i++) {            result = preTwo + preOne ;            preTwo = preOne ;            preOne = result ;        }        return result ;    }};

第二次做:
以来依然想到了递归,然后写下了如下测试代码:
// 3.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"class Solution {public:int Fibonacci(int n) {if (n == 0) return 0;if (n == 1) return 1;return Fibonacci(n - 1) + Fibonacci(n - 2);}};int _tmain(int argc, _TCHAR* argv[]){Solution s;int result = s.Fibonacci(10);return 0;}

提示我运行超时:您的程序未能在规定时间内运行结束,请检查是否循环有错或算法复杂度过大。
还是用迭代版吧:
class Solution {public:    int Fibonacci(int n) {        if ( n <= 0 ) return 0 ;        if ( n == 1 ) return 1 ;                int first = 0 ;        int second = 1 ;        int result = 0 ;                for ( int i = 2; i <= n; ++ i ) {            result = first + second ;            first = second ;            second = result ;        }                return result ;    }};

第三次做:
class Solution {public:    int Fibonacci(int n) {if ( n <= 0 ) return 0 ;        if ( n == 1 ) return 1 ;                int first = 0 ;        int next = 1 ;        int cur ;                for ( int i = 2; i <= n; ++ i ) {            cur = first + next ;            first = next ;            next = cur ;        }        return cur ;    }};


0 0
原创粉丝点击