[DP]509. Fibonacci Number

2021/7/17 6:05:21

本文主要是介绍[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



这篇关于[DP]509. Fibonacci Number的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程