1. 程式人生 > >Java遞迴練習

Java遞迴練習

public class TestDiGui {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println(f(5));
        for (int i = 1; i <= 20; i++) {
            System.out.print(f(i) + " ");
        }
        System.out.println();
        System.out.println("=====================");
        System.out.println(f(5));
        for (int i = 1; i <= 20; i++) {
            System.out.print(f2(i) + " ");
        }
    }

    /**
     * 遞迴演算法實現
     * 
     * @param n
     * @return
     */
    public static long f(int n) {
        if (n == 1 || n == 2) {
            return 1;
        } else {
            return f(n - 1) + f(n - 2);
        }
    }

    /**
     * 非遞迴實現
     * 
     * @param n
     * @return
     */
    public static long f2(int n) {
        int[] a = new int[n + 1];
        a[0] = 0;
        a[1] = 1;
        for (int i = 2; i <= n; i++) {
            a[i] = a[i - 1] + a[i - 2];
        }
        return a[n];
    }

}

結果:

5
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 
=====================
5
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765