递归基础练习(上)

菜鸟日记—1月22日

什么是递归?

就是不断调用自身

  • 1.找重复: 找子问题 比如求n的阶乘子问题是–求n-1的阶乘
  • 2.找变化: 变化的量作为参数
  • 3.找边界: 出口 在何时结束

案例一:求n的阶乘

//1.求阶乘
    static int f1(int n){
    
    
        if (n == 1){
    
    
            return 1;
        }
        return n * f1(n - 1);
    }
public class 递归基础练习 {
    
    
    public static void main(String[] args) {
    
    
        System.out.println(f1(3));
        }

案例二:打印 i — j

//2.打印i--j
    static void f2(int i,int j){
    
    
        if (i > j){
    
    
            return;
        }
        System.out.println(i);
        f2(i + 1,j);
    }
public class 递归基础练习 {
    
    
    public static void main(String[] args) {
    
    
		f2(1,10);
		}

案例三:求数组和

static int f3(int[] arr,int index){
    
    
        if (index == arr.length - 1){
    
    
            return arr[index];
        }
        return arr[index] + f3(arr,index + 1);
    }
public class 递归基础练习 {
    
    
    public static void main(String[] args) {
    
    
		System.out.println(f3(new int[]{
    
    1,2,3,4,5,6,7,8,9,10},0));
		}

案例四:字符串翻转

static String f4(String src,int index){
    
    
        if (index == 0){
    
    
            return "" + src.charAt(0);
        }
        return src.charAt(index) + f4(src,index - 1);
public class 递归基础练习 {
    
    
    public static void main(String[] args) {
    
    
		System.out.println(f4("abcdefg",6));
		}

猜你喜欢

转载自blog.csdn.net/ghl971/article/details/113000585