实现斐波那契数列的两种方式(递归和数组)

import sun.misc.Launcher;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description
 * @Author lxh
 * @Date 2021/4/20 2:49 下午
 */
public class Demo {



    public static void main(String[] args) throws Exception {
        for (int i = 1; i <= 9; i++) {
            int result = handleFib(i);
            System.out.print(result + " ");
        }
        System.out.println();
        handleFibAnother(9);

    }


    private static void handleFibAnother(int n) {

        int[] array = new int[n];
        for (int i = 0; i < n ; i++) {
            if (i == 0 || i == 1) {
                array[i] = 1;
            }else {
                array[i] = array[i - 1] + array[i - 2];
            }
            System.out.print(array[i] + " ");
        }


    }


    private static int handleFib(int n) {
        if (n == 1 || n == 2) {
            return 1;
        }
        return handleFib(n - 1) + handleFib(n - 2);
    }





}


posted @ 2021-07-05 16:42  鹿小虎  阅读(164)  评论(0)    收藏  举报