線性結構(遞歸)

簡單的實現

package LinearStructure;

/**
 * @author lhc
 * @Title: Recursion
 * @ProjectName dataStructure
 * @Description: 遞歸
 * @date 2019/1/4下午 5:28
 */
public class Recursion {

    public static void main(String[] args) {
        print(10000);
    }

    public static void print(int i) {
        if (i > 0) {
            System.out.println(i);
            print(i - 1);
        }
    }

}

斐波那契數列

package LinearStructure;

/**
 * @author lhc
 * @Title: Fobonacie
 * @ProjectName dataStructure
 * @Description: 斐波那契數列
 * @date 2019/1/4下午 5:47
 */
public class Fobonacie {

    public static void main(String[] args) {
        int a = feibonaci(20);
        System.out.println(a);
    }

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

漢諾塔

package LinearStructure;

/**
 * @author lhc
 * @Title: Hanoi
 * @ProjectName dataStructure
 * @Description: 漢諾塔
 * @date 2019/1/5下午 9:39
 */
public class Hanoi {
    public static void main(String[] args) {
        hanioTest(5, "A", "B", "C");
    }

    /**
     * @param n    盤子數量
     * @param from 開始的柱子
     * @param in   中間的柱子
     * @param to   目標柱子
     */
    public static void hanioTest(int n, String from, String in, String to) {
        if (n == 1) {
            System.out.println("第1個盤子從" + from + "移到" + to);
        } else {
            hanioTest(n - 1, from, to, in);
            System.out.println("第" + n + "個盤子從" + from + "移到" + to);
            hanioTest(n - 1, in, from, to);
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章