Climbing Stairs

本文介绍了一种解决爬楼梯问题的方法,通过递归和动态规划两种方式计算达到楼梯顶部的不同路径数量。递归方法虽然直观但容易超时,而动态规划方法则能够高效解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


/**
 * 
 * <p>
 * ClassName ClimbingStairs
 * </p>
 * <p>
 * Description You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps.
 * In how many distinct ways can you climb to the top?
 * </p>
 * 
 * @author TKPad wangx89@126.com
 *         <p>
 *         Date 2015年3月19日 下午9:18:24
 *         </p>
 * @version V1.0.0
 *
 */
public class ClimbingStairs {
    public int climbStairs(int n) {
        if (n <= 0) {
            return 0;
        }
        // n步到顶,在n步中,你可以走一步或者两步,一共有多少种走法
        if (1 == n || 2 == n) {// 一级台阶,只有一种走法
            // 两级台阶,有两种走法
            return n;
        }
        return climbStairs(n - 1) + climbStairs(n - 2);// 这样做超时

    }

    public int climbStairs2(int n) {
        int[] num = new int[n + 1];
        num[0] = 1;
        num[1] = 1;
        for (int i = 2; i <= n; i++) {
            num[i] = num[i - 1] + num[i - 2];
        }
        return num[n];// 这样就不会超时了
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        // System.out.println(new ClimbingStairs().climbStairs(26));
        System.out.println(new ClimbingStairs().climbStairs2(45));
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值