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);
    }
  • 相关阅读:
    空心杯 电机
    scikit learn 安装
    python fromkeys() 创建字典
    python 清空列表
    mac最常用快捷键
    php while循环
    php 获取某个日期n天之后的日期
    php 添加时间戳
    php 格式化时间
    php 数值数组遍历
  • 原文地址:https://www.cnblogs.com/mufeng07/p/12674059.html
Copyright © 2011-2022 走看看