java代碼實現遞歸


think in java 書中使用遞歸分析

代碼如下:

public class Snake implements Cloneable {
    private Snake next;
    private char c;
    // Value of i == number of segments
    Snake(int i, char x) {
        c = x;
        if(--i > 0)
            next = new Snake(i, (char)(x + 1));
    }
    void increment() {
        c++;
        if(next != null)
            next.increment();
    }
    public String toString() {
        String s = ":" + c;
        if(next != null)
            s += next.toString();
        return s;
    }
    public Object clone() {
        Object o = null;
        try {
            o = super.clone();
        } catch (CloneNotSupportedException e) {}
        return o;
    }
    public static void main(String[] args) {
        Snake s = new Snake(5, 'a');
        System.out.println("s = " + s);
        Snake s2 = (Snake)s.clone();
        System.out.println("s2 = " + s2);
        s.increment();
        System.out.println(
                "after s.increment, s2 = " + s2);
    }
}

示意圖如下:

snake.png

輸出如下:

s = :a:b:c:d:e
s2 = :a:b:c:d:e
after s.increment, s2 = :a:c:d:e:f

分析:

  • 在講clone()的時候,為說明淺復制,舉例此類;

一條 Snake(蛇)由數段構成,每一段的類型都是 Snake。所以,這是一個一段段鏈接起來的列表。
所有段都是以循環方式創建的,每做好一段,都會使第一個構建器參數的值遞減,直至最終為零。
而為給每段賦予一個獨一無二的標記,第二個參數(一個 Char )的值在每次循環構建器調用時都會遞增。
increment()方法的作用是循環遞增每個標記,使我們能看到發生的變化;
而 toString 則循環打印出每個標記。

使用遞歸打印階乘

@Test
public void test() {
    //10! = 10 * 9 * 8 * 。。。。1;
    System.out.println(get(36));
}
public static long get(int n) {
    long result = 1;
    if (n == 1) {
        result *= 1;
    }
    else {
        result = n * get(n-1);
    }
    return result;
}


使用遞歸打印斐波那契數列

    //第一和第二項是1,后面每一項是前二項之和,即1,1,2,3,5,8,13,...。
    //遞歸實現:
    public static int fun02(int n) {//n是第n個數,從 0 開始
        if (n > 1) {
            return (fun02(n-1) + fun02(n-2));
        }else {
            return 1;
        }
    }
    public static void main(String[] args) {
        for (int i = 0; i <= 9; i++) {
            System.out.println(fun02(i));
        }
    }

使用遞歸打印 9 * 9乘法口訣表

public class multiplication99 {

    @Test
    public void test(){
        //getByFor(9);
        getByRecursion(9);
    }

    public static void getByFor(int n) {//for 循環實現
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(i+" * "+j+" = "+i*j+" ");
            }
            System.out.println();
        }
    }

    public static void getByRecursion(int n) {//遞歸 實現
        if (n == 1) {
            System.out.println("1 * 1 = 1 ");
        }
        else {
            getByRecursion(n-1);
            for (int j = 1; j <= n; j++) {
                System.out.print(n+" * "+j+" = "+n*j+" ");
            }
            System.out.println();
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM