递归算法

来源:互联网 发布:网络是个虚拟世界英语 编辑:程序博客网 时间:2024/06/03 12:31

概念:递归算法是一种直接或者间接调用自身函数或者方法的算法

简单应用

public static void test(int n){        System.out.println(n);        s+=n;        if(n == 0){            System.out.println(s);            return;        }        test(n-1);    }

三角数字应用

第一项为1 第n项为 n +【(n-1)项的值】规律就是 n=n*(n+1)/2
//方法1:public static int test1(int n){        if(n == 1){            return 1;        }else{            return n + test1(n-1);        }    }//方法2:public static int test1(int n){        s +=n;        n--;        if( n <=0){            System.out.println(s);            return;        }        test1(n);    }

fibonacci数列

第一项为0;第二项为1;第n项为第(n-1)项的值+第(n-2)项的值
    public static int test2(int n){        if(n <= 0){            System.out.println("数字不能小于1");            return -1;        }        else if(n == 1){            return 0;        }        else if(n == 2){            return 1;        }        else {            return test2(n-1)+test2(n-2);        }    }

HanoiTower汉诺塔

有一个梵塔,塔内有三个座A、B、C,A座上有诺干个盘子,盘子大小不等,大的在下,小的在上(如图)。把这些个盘子从A座移到C座,中间可以借用B座但每次只能允许移动一个盘子,并且在移动过程中,3个座上的盘子始终保持大盘在下,小盘在上。
/**     * @Description HanoiTower汉诺塔     * @param topN 盘子数     * @param from 起始位置     * @param inter 中间位置     * @param aim 目标位置     */    public static void hanoiTower(int topN,char from,char inter,char aim){        if(topN == 1){            System.out.println("盘子--1从"+from+"塔座移到"+aim+"塔座");        }        else{            hanoiTower(topN-1, from, aim, inter);            System.out.println("盘子"+topN+"从"+from+"塔座移到"+aim+"塔座");            hanoiTower(topN-1, inter, from, aim);        }    }
原创粉丝点击