• [DP]509. Fibonacci Number


    509. Fibonacci Number

    Difficulty: 简单

    The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,

    F(0) = 0, F(1) = 1
    F(n) = F(n - 1) + F(n - 2), for n > 1.
    

    Given n, calculate F(n).

    Example 1:

    Input: n = 2
    Output: 1
    Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
    

    Example 2:

    Input: n = 3
    Output: 2
    Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
    

    Example 3:

    Input: n = 4
    Output: 3
    Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
    

    Constraints:

    • 0 <= n <= 30

    Solution 1

    Language: c++

    ​class Solution {
    public:
        int fib(int n) {
            if(n == 0 || n == 1)
                return n;
            else
                return fib(n-1)+fib(n-2);
        }
    };
    

    Language: python

    class Solution:
        def fib(self, n: int) -> int:
            if n == 1 or n == 0:
                return n
            else:
                return self.fib(n-1) + self.fib(n-2)
    

    使用递归的,重复计算了很多次,不过考虑到不超过30次,其实还能接受,但是如果能记录下重复计算的结果,使用空间换时间的思路。

    Solution 2

    Language: c++

    class Solution {
    public:
        int fib(int n) {
            if (n == 0 || n == 1)
                return n;
            int a = 0,b = 1;
            for(int i = 2;i<=n;++i){
                b = a + b;
                a = b - a;
            }
            return b;
        }
    };
    

    Language: python

    class Solution:
        def fib(self, n: int) -> int:
            if n == 1 or n == 0:
                return n
            a,b=0,1
            for i in range(1,n):
                b = a + b
                a = b - a
            return b
    

    去除掉重复的计算,速度也会快不少,使用的空间也只有O(1)。


    最后贴出出lc的运行消耗对比
    consumption

  • 相关阅读:
    留言板
    移动端开发
    css3的伪类
    JQuery移除事件
    关于offset,你知道多少?
    关于section-scroll插件:
    jQuery响应式弹出层和对话框插插件magnific-popup.css
    col-lg-8 col-lg-offset-2
    关于渐变属 gradient:
    关于 window.onresize
  • 原文地址:https://www.cnblogs.com/Swetchine/p/15022394.html
Copyright © 2020-2023  润新知