经典递归问题(2)

2018-10-23  本文已影响0人  jiamjg
反转串

求一个字符串相应的反转串。

public class 递归7_反转串 {
    public static void main(String[] args){
        String string1="abc";
        System.out.println(reverseString(string1));
    }
    public static String reverseString(String x){
        if(x==null||x.length()<2){
            return  x;
        }
        return  reverseString(x.substring(1))+x.charAt(0);
    }
}

杨辉三角

public class 递归8_杨辉三角 {
    public static void main(String[] args){
        int level=6; //一共有6层
        for(int i=0;i<5;i++){
            for(int j=0;j<=i;j++){
                System.out.print(f(i,j)+" ");
            }
            System.out.println();
        }
        
    }
    //杨辉三角第m层的第n个元素
    public static int f(int m,int n){
        if(n==0||m==n){
            return 1;
        }
        return f(m-1,n)+f(m-1,n-1);
    }
}

计算3个A、2个B可以组成多少种排列的问题(如:AAABB,AABBA)是《组合数学》的研究领域,但有些情况下,也可以利用计算机计算速度快的特点通过巧妙的推理来解决问题,求m个A,n个B可以组成多少种不同的排列。

思路:要计算m个A,n个B有多少种排列可以假设第一个字符是A,计算m-1个A,n个B和假设第一个字符是B,计算m个A,n-1个B有多少种排列情况,如果其中的一个等于零,那么肯定只有一种排列情况。

public class 递归9_求排列组合的数目 {
    public static void main(String[] args){
        System.out.println(f(3,2));
    }
    public static int f(int m,int n){
        if(m==0||n==0){
            return 1;
        }
        return f(m-1,n)+f(m,n-1);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读