zoukankan      html  css  js  c++  java
  • [LeetCode] 509. Fibonacci Number

    Easy

    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: 2
    Output: 1
    Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
    

    Example 2:

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

    Example 3:

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

    Note:

    0 ≤ N ≤ 30.

    题目大意:满足以下条件的数列F称为斐波那契数列:

    1.F(0)=0,F(1)=1;

    2.F(n)=F(n-1)+F(n-2);

    给出一个数字x,求出F(x)的值。

    方法:菲波那切数列除了初始条件n=0和n=1的值以外,其他的项的值都是由该项的前两项决定的,所以这是一个动态规划的问题。

    方法一:递归法

    递归的终止条件由斐波那契数列的初始值决定,即当n=0时结果为0,n=1时结果为1.

    代码如下:

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

    方法二:迭代法

    由菲波那切数列的性质,使用循环逐个计算知道求出目标项的值。我们可以维护一个有两项的向量,下一项的值就有这两项求出。初始值n=0和n=1还是要先给出。

    一次循环更新两项:

    我们由更新结果可以看出循环次数为N/2,每次循环N的值要更新为N-2.这样就能保证结果在我们维护的这个向量当中。如果N为偶数则结果为第一项,如果N为奇数结果为第二项。

    值得注意的是,向量更新时的顺序,由上图为例,F(2)由F(0)和F(1)求出,而F(3)由F(1)和F(0)求出,所以要先更新向量的第一项,再更新第二项。切忌交换顺序。

    代码如下:

    class Solution {
    public:
        int fib(int N) {
            if(N==0 || N==1)return N;
            
            vector<int> fib={0,1};
            while(N/2){
                fib[0]=fib[0]+fib[1];
                fib[1]=fib[0]+fib[1];
                N-=2;
            }
            return N==0?fib[0]:fib[1];
        }
    };
  • 相关阅读:
    mitm iptables ssltrip set ferret hamster
    SQL注入的常用函数和语句
    SQL注入的字符串连接函数
    SQL注入的分类
    DNS配置详解
    Linux的任务计划--cron入门
    Linux文件系统层次结构标准
    Linux的awk命令
    Linux的sed命令
    Linux的find命令
  • 原文地址:https://www.cnblogs.com/cff2121/p/11577334.html
Copyright © 2011-2022 走看看