笔记2-斐波那契数列

斐波那契数列:

package com.mj;

public class Main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        
        System.out.println(fib2(46));
    }
    
    //递归法 50之后卡住
    public static int fib1(int n) {
        if (n<=1) return n;
        
        return fib1(n-1)+fib1(n-2);
    }
    
    //非递归
    public static int fib2(int n) {
        if (n<=1) return n;
        
        int first = 0;
        int second = 1;
        for (int i = 0; i < n-1; i++) {
            int sum = first + second;
            first = second;
            second = sum;
        }
        return second;
    }
    
    //优化
    public static int fib3(int n) {
        
        if (n<=1) return n;
        
        int first = 0;
        int second = 1;
        while (n-- > 1) {
            second += first;
            first = second - first;
        }
        return second;
        
    }

}

此文仅为鄙人学习笔记之用,朋友你来了,如有不明白或者建议又或者想给我指点一二,请私信我。liuw_flexi@163.com/QQ群:582039935. 我的gitHub: (学习代码都在gitHub) https://github.com/nwgdegitHub/
原文地址:https://www.cnblogs.com/liuw-flexi/p/13491401.html