java data structures and algorithms (07) Fibonacci number

  • We all know that Fibonacci number, and now asked to enter an integer n, you output the n-th Fibonacci number Fibonacci sequence of item (from 0, the first 0 is 0). n <= 39. Complete the following code:
public class Solution {
    public int Fibonacci(int n) {

    }
}
复制代码
  • Idea: simple, classic recursion
  • Code
public class Solution {
    public int Fibonacci(int n) {
        if (n < 1) {
            return 0;
        } else if (n == 1 || n == 2) {
            return 1;
        } else {
            return Fibonacci(n - 1) + Fibonacci(n - 2);
        }
    }
}
复制代码

Reproduced in: https: //juejin.im/post/5cf5d6255188253456691897

Guess you like

Origin blog.csdn.net/weixin_34198762/article/details/91415258