方法递归(黑马)

public static void main(String[] args) {
        test1();
    }

    public static void test1(){
        System.out.println("----test1----");
        test1();
    }

    public static void test2(){
        System.out.println("----test2----");
        test3();
    }

    private static void test3() {
        test2();
    }

递归算法三要素:

  •  递归的公式:f(n) = f(n - 1) * n
  • 递归的终结点:f(1)
  • 递归的方向必须走向终结点

  • 案例:用方法递归计算阶乘
public static void main(String[] args) {
        System.out.println(f(5));
    }

    public static int f(int n) {
        if(n == 1){
            return 1;
        }else{
            return f(n - 1) * n;
        }

    }
  • 递归求1-n的和
 public static void main(String[] args) {
        System.out.println(f(5));
    }

    public static int f(int n) {
        if(n == 1){
            return 1;
        }else{
            return f(n - 1) + n;
        }

    }
  • 猴子吃桃问题
 public static void main(String[] args) {
        //猴子吃桃问题:后一天吃的都是前一天桃子数量的一半再减一个
        //f(x) - f(x) / 2 - 1 = f(x + 1) x是天数
        //2f(x) - f(x) - 2 = 2f(x + 1)
        //f(x) = 2f(x + 1) + 2
        System.out.println(f(1));
        System.out.println(f(2));
        System.out.println(f(3));
        System.out.println(f(4));
        System.out.println(f(5));
    }

    public static int f(int x) {
        if(x == 10){
            return 1;
        }else{
            return 2 * f(x + 1) + 2;
        }

    }

  • 14
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值