java, 爬楼梯(使用递归)

可爱的小明特别喜欢爬楼梯,他有的时候一次爬一个台阶,有的时候一次爬两个台阶。如果这个楼梯有20个台阶,小明一共有多少种爬法呢?(爬上去后就不能再下来)

运算结果:

1层台阶 ---> 1种爬法

2层台阶 ---> 2种爬法

7层台阶 ---> 21种爬法

方法一: 使用递归完成


/*可爱的小明特别喜欢爬楼梯,他有的时候一次爬一个台阶,有的时候一次爬两个台阶。
如果这个楼梯有20个台阶,小明一共有多少种爬法呢?(爬上去后就不能再下来)*/
//第二层台阶以后, 下一阶的爬法等于前两阶之和

public class Test4 {
    public static void main(String[] args) {
        System.out.println(getCount(20));

    }

    private static int getCount(int stairs) {
        if (stairs==1){
            return 1;
        }
        if (stairs==2){
            return 2;
        }
        return getCount(stairs-1)+getCount(stairs-2);
    }
}

方法二: 不使用递归, 通过循环搭配数组的存储, 在数组中存每一层楼梯的爬法

public class StairsClimbingWays {

    public static void main(String[] args) {
        // 计算小明爬20个台阶的方法数
        int n = 20;
        System.out.println("小明有 " + climbStairs(n) + " 种爬法。");
    }

    // 使用动态规划计算斐波那契数列
    public static int climbStairs(int n) {
        if (n <= 2) {
            return n;
        }
        
        int[] ways = new int[n + 1];
        // 初始化前两个台阶的走法
        ways[1] = 1;
        ways[2] = 2;

        for (int i = 3; i <= n; i++) {
            // 当前台阶的走法是前三个台阶走法的总和
            ways[i] = ways[i - 1] + ways[i - 2];
        }
        
        return ways[n];
    }
}

举一反三: 还有的时候可以一次爬三个台阶, 如果这个楼梯有20个台阶,小明一共有多少种爬法?

/*可爱的小明特别喜欢爬楼梯,他有的时候一次爬一个台阶,有的时候一次爬两个台阶, 还有的时候一次爬三个台阶
如果这个楼梯有20个台阶,小明一共有多少种爬法呢?(爬上去后就不能再下来)*/
//第三层台阶以后, 下一阶的爬法等于前三阶之和

public class Test3 {
    public static void main(String[] args) {
        System.out.println(getCount(20));

    }

    private static int getCount(int stairs) {
        if (stairs==1){
            return 1;
        }
        if (stairs==2){
            return 2;
        }
        if (stairs==3){
            return 4;
        }
        return getCount(stairs-1)+getCount(stairs-2)+getCount(stairs-3);
    }
}

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值