[算法] - 斐波那契数列

2021-06-17 19:51:41 浏览数 (1)

牛客网 NC65-斐波那契数列

两种实现

  • 迭代
代码语言:javascript复制
public class Solution {
    public int Fibonacci(int n) {
        if(n == 0 || n == 1){
            return n;
        }
        
        int a = 0;
        int b = 1;
        int fib = 0;
        for(int i = 2; i <= n; i  ){
            fib = a   b;
            a = b;
            b = fib;
        }
        
        return fib;
    }
}
  • 递归
代码语言:javascript复制
public class Solution {
    public int Fibonacci(int n) {
        if(n == 0 || n == 1){
            return n;
        }
        
        return Fibonacci(n-1)   Fibonacci(n-2);
    }
}

0 人点赞