递归学习

package test;

public class TestDiGui {

    public static void main(String[] args) {
        //System.out.println(jiecheng(10));
        //System.out.println(fbnq(9));
        int nDisks = 2;
        moveDish(nDisks, 'A', 'B', 'C');
    }

    //阶层递归算法
    private static int jiecheng(int n) {
        if (n == 1) {
            return 1;
        }
        return n * jiecheng(n - 1);
    }

    //这里有一组数:1、1、2、3、5、8、13、21、34、55......要求计算用这个递归算法,计算出这组数的第40个数是多少
    private static int fbnq(int i) {
        if (i == 0) {
            return 0;
        } else if (i == 1 || i == 2) {
            return 1;
        } else {
            return fbnq(i - 1) + fbnq(i - 2);
        }
    }

    //汉诺塔
    //为了将N个盘子从A移动到C,需要先将第N个盘子上面的N-1个盘子移动到B上,这样才能将第N个盘子移动到C上。同理,
    //为了将第N-1个盘子从B移动到C上,需要将N-2个盘子移动到A上,这样才能将第N-1个盘子移动到C上。通过递归就可以实现汉诺塔问题的求解。
    public static void moveDish(int level, char from, char inter, char to) {
        if (level == 1) {
            System.out.println("从" + from + " 移动盘子" + level + " 号到" + to);
        } else {
            moveDish(level - 1, from, to, inter);
            System.out.println("从" + from + " 移动盘子" + level + " 号到" + to);
            moveDish(level - 1, inter, from, to);
        }
    }
}

posted on 2016-09-30 08:53  甘蔗的味道  阅读(132)  评论(0)    收藏  举报

导航