• lintcode:Fibonacci 斐波纳契数列


    题目:

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

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

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

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

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

    样例

    给定 1,返回 0

    给定 2,返回 1

    给定 10,返回 34

    解题:

    好像很简单的。。。递归是最简单的,貌似很耗时,结果:Time Limit Exceeded

    Java程序:

    递归程序

    class Solution {
        /**
         * @param n: an integer
         * @return an integer f(n)
         */
        public int fibonacci(int n) {
            // write your code here
            if(n==1)
                return 0;
            else if(n==2)
                return 1;
            else //if(n>2)
                return fibonacci(n-1) + fibonacci(n-2);
        }
    }
    View Code

    非递归:

    class Solution {
        /**
         * @param n: an integer
         * @return an integer f(n)
         */
        public int fibonacci(int n) {
            // write your code here
            if(n==1)
                return 0;
            if(n==2)
                return 1;
            int f0 = 0;
            int f1 = 1;
            int i = 3;
            int f = 0;
            while(i<=n){
                f = f0 + f1;
                f0 = f1;
                f1 = f;
                i++;
            }
            return f;
        }
    }
    View Code

    总耗时: 1176 ms

    哦,对了还可以直接根据斐波那契数列公式计算:

    Python程序:

    class Solution:
        # @param n: an integer
        # @return an integer f(n)
        def fibonacci(self, n):
            # write your code here
            if n==1:
                return 0
            elif n==2:
                return 1;
            f0 = 0
            f1 = 1
            f = 0
            i = 3
            while i<=n:
                f = f0 + f1
                f0 = f1
                f1 = f
                i+=1
            return f 
    View Code

    总耗时: 205 ms

  • 相关阅读:
    正则表达式30分钟入门教程
    21 个HTML网页转RSS Feeds的工具
    批量去除PHP文件中bom的PHP代码
    WEB网页采集技术参考
    xcache
    Sonix SN9P701 OCR点读笔二维码识别源码
    UI设计素材资源网站推荐
    解决电信DNS劫持
    自学电子技术的最佳方法
    wp资源汇总
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4886321.html
Copyright © 2020-2023  润新知