Java台阶递归

蓝桥杯:
小明刚刚看完电影《第39级台阶》,离开电影院的时候,他数了数礼堂前的台阶数,恰好是39级!
站在台阶前,他突然又想着一个问题:
如果我每一步只能迈上1个或2个台阶。先迈左脚,然后左右交替,最后一步是迈右脚,也就是说一共要走偶数步。那么,上完39级台阶,有多少种不同的上法呢?
请你利用计算机的优势,帮助小明寻找答案。

public class Main06台阶递归 {
    static int count=0;
    static int temp=0;
    static void fun(int stair ,int step){

        if (stair<0){temp++;return;} //如果 台阶数小于零 即走完
        if (stair==0){
            //不论何种情况 stair最终都是0
            //判断台阶数等于零的时候判断是否是偶数 如果是 就 count++
            temp++;
            if (step%2==0){
                count++;
            }
        }
        //递归
        fun(stair-1,step+1);
        fun(stair-2,step+1);
    }

    public static void main(String[] args) {
            fun(39,0);
            System.out.printf("count=%d\t",count);
        System.out.println(temp);
    }
}

洛谷(洛谷里面的这个题用递归会超时,仅供参考):
题目描述
楼梯有 N 阶,上楼可以一步上一阶,也可以一步上二阶。
编一个程序,计算共有多少种不同的走法。

public class P1255 {
    static Scanner sc=new Scanner(System.in);
    static int step=sc.nextInt();
    static  int count=0;
    static  int stages=0;
    public  static void dfs(int step,int stages ){
        if (stages>step){
            return;
        }
        if (stages==step){
            count++;
            return;
        }
            dfs(step,stages+1);
            dfs(step,stages+2);

    }

    public static void main(String[] args) {
        dfs(step,stages);
        System.out.println(count);
    }

}

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值