经典算法题之——爬楼梯

话不多说先上原题:
在这里插入图片描述
以下我将会以四种方法来解题,自行分析递归调用的弊端:

package com.爬楼梯;

/*
 * 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
 *
 * 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
 *
 * 注意:给定 n 是一个正整数。
 */
public class Solution {
    public static void main(String[] args) {
        long start1 = System.currentTimeMillis();
        System.out.println(palou(40));
        long end1 = System.currentTimeMillis();
        System.out.println("for循环算时间:"+(end1-start1));

        long start2 = System.currentTimeMillis();
        System.out.println(palou2(40));
        long end2= System.currentTimeMillis();
        System.out.println("while循环算时间:"+(end2-start2));

        long start3 = System.currentTimeMillis();
        System.out.println(palou3(40));
        long end3= System.currentTimeMillis();
        System.out.println("递归方法(一)时间:"+(end3-start3));

        long start4 = System.currentTimeMillis();
        System.out.println(climb_Stairs(0, 40));
        long end4= System.currentTimeMillis();
        System.out.println("递归方法(二)时间:"+(end4-start4));
    }


    public static int palou(int n){
        int result = 0;
        int f1 = 1;
        int f2 = 2;
        if (n == 1||n==2) {
            return n;
        }
        //指针前移
        for (int i = 3; i <= n; i++) {
            result = f1 + f2;
            f1 = f2;
            f2 = result;
        }
        return result;
    }
    public static int palou2(int n){
        if (n == 1||n==2) {
            return n;
        }
        else {
            int res = 0;
            int i = 1, j = 2;
            int k = 3;
            while (k <= n) {
                res = i + j;
                i = j;
                j = res;
                k++;
            }
            return res;
        }
    }
    //递归方法自己调用自己(所用时间长)

    /**
     * 比如要求Y4 = Y3 + Y2 = Y2 + Y1 + Y1 + Y0
     *
     *不断推进,直到基准情形
     *
     */
    public static int climb_Stairs(int i, int n) {
        if (i > n) {
            return 0;
        }
        if (i == n) {
            return 1;
        }
        return climb_Stairs(i + 1, n) + climb_Stairs(i + 2, n);
    }

    public static int palou3(int n) {
        if (n == 1 || n == 2) {
            return n;
        }
        return palou3(n-1) +palou3(n-2);
    }
}

运行结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值