算法18(递归)-斐波拉契数列

题目:
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.

采用递归的方法,秒解这道题:代码中也有详细的描述

public class FibonacciSequence {

  //1.函数是用来干什么的:计算f(N)
  //2.函数结束条件是什么:当n为0或者为1的时候就应该结束
  //3.寻找函数的等式或者给下一层返回的是什么:f(n) = f(n-1) + f(n-2)

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


  public static void main(String[] args) {
    FibonacciSequence sequence = new FibonacciSequence();
    int i = sequence.fib(3);
    System.out.println(i);
  }
}

做递归题就按照我这种套路来进行做就比较好理解,不要在意递归里面的具体细节,只需关注这个等式,以及停止的一个条件。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/fibonacci-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1371769065@qq.com

文章标题:算法18(递归)-斐波拉契数列

字数:329

本文作者:一叶知秋

发布时间:2020-07-04, 16:31:47

最后更新:2020-07-04, 16:33:53

原始链接:http://yoursite.com/2020/07/04/arithmtic/18-%E9%80%92%E5%BD%92/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

×

喜欢就点赞,疼爱就打赏

相册 github