zoukankan      html  css  js  c++  java
  • [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

  • 相关阅读:
    HTML基础学习笔记
    CSS-精灵图片的使用(从一张图片中截图指定位置图标)
    侧边栏显示
    HTML <form> action 属性
    2018年寒假小记
    算法提高--接水问题
    基础练习--huffman
    ...
    基础算法
    枚举--最长单词--蓝桥杯
  • 原文地址:https://www.cnblogs.com/Swetchine/p/15022394.html
Copyright © 2011-2022 走看看