zoukankan      html  css  js  c++  java
  • Java递归小程序

    /**
     * 三角数字之和 ...5+4+3+2+1
     * @param n
     * @return
     */
    public int triangle(int n){
        if(n==1){
            return 1;
        }
        return n+triangle(n-1);
    }
    
    /**
     * 阶乘 5!
     * @param n
     * @return
     */
    public int factorial(int n){
        if(n==1){
            return 1;
        }
        return n*factorial(n-1);
    }
    
    /**
     * 递归二分查找
     * @param a
     * @param findKey
     * @return
     */
    public int recFind(int[] a,int findKey,int low,int high){
        int mid=(low+high)/2;
        if(a[mid]==findKey){
            return mid;
        }else if(low>mid){
            return -1;
        }else{
            if(a[mid]<findKey){
                return recFind(a,findKey,mid+1,high);
            }else{
                return recFind(a,findKey,low,mid-1);
            }
        }
    }
    
    /**
     * 汉诺塔问题
     * @param topN
     * @param from
     * @param inter
     * @param to
     */
    public void doTower(int topN,char from,char inter,char to){
        num++;
        if(topN==1){
            System.out.println("Disk 1 from "+from+" to "+to);
        }else{
            doTower(topN-1,from,to,inter);
            System.out.println("Disk "+topN+" from "+from+" to "+to);
            doTower(topN-1,inter,from,to);
        }
        System.out.println(num);
    }
  • 相关阅读:
    动态规划训练之十
    数据结构训练之一
    图论训练之八
    数论训练之三
    动态规划训练之九
    动态规划训练之八
    动态规划训练之七
    杂题训练之三
    图论训练之七
    动态规划训练之六
  • 原文地址:https://www.cnblogs.com/mufeng07/p/12674059.html
Copyright © 2011-2022 走看看