• [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

  • 相关阅读:
    今天入住博客园,希望有个好的开始,自己在这边可以学习成长
    浅谈 C# ref 和 out 的使用方法
    类之间的几种关系
    VB6.0 文件日志读取
    基于NPOI的Excel导入和导出功能
    WebService的创建,发布与调用
    C# OfType 的使用
    Vb6.0 文件日志记录
    ZipInputStream
    [转载]遗传算法入门
  • 原文地址:https://www.cnblogs.com/Swetchine/p/15022394.html
Copyright © 2020-2023  润新知