递推算法-斐波那契数列(兔子繁殖)

1、

 int a = 1, b = 1, c = 0;
        System.out.println("斐波那契数列前20项为:");
        System.out.print(a + "\t" + b + "\t");
        //因为前面还有两个1、1 所以i<=18
        for (int i = 1; i <= 18; i++) {
            c = a + b;
            a = b;
            b = c;
            System.out.print(c + "\t");
        }

2、

  int arr[] = new int[20];
        arr[0] = arr[1] = 1;
        for (int i = 2; i < arr.length; i++) {
            arr[i] = arr[i - 1] + arr[i - 2];
        }
        System.out.println("斐波那契数列的前20项如下所示:");
        for (int i = 0; i < arr.length; i++) {

            System.out.print(arr[i] + "\t");
        }

3、此处已经用到递归

   System.out.println("斐波那契数列的前20项为:");
        for (int j = 1; j <= 20; j++) {
            System.out.print(getFibo(j) + "\t");

        }
    }



    private static int getFibo(int i) {
        if (i == 1 || i == 2)
            return 1;
        else
            return getFibo(i - 1) + getFibo(i - 2);
    }

你可能感兴趣的:(数据结构与算法)