Leetcode climbing-stair

本文探讨了经典的爬楼梯问题,给出了两种不同的解决方案:一种是递归方法,但时间复杂度过高;另一种是非递归方法,通过循环实现,效率更高。通过对这两种方法的时间性能进行对比测试,展示了非递归方法在处理大数据时的优势。

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

此题不难,首先先写出递归的方法:
上第n层台阶是有两种情况
1,一步上去
2,跨两步上去
即climbStair(n)=climbStair(n-1)+climbStair(n-1)
即可得到他的递归方法。
根据递归方法写出循环的方法即可

/**********************************************************************************
*
* 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?
*
*
**********************************************************************************/

#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <vector>
using namespace std;
int climbStairs(int n) {
    if (n <= 3) return n;
    int a[2] = { 2,3 };
    for (int i = 4; i <= n; i++) {
        int t = a[0] + a[1];
        a[0] = a[1];
        a[1] = t;
    }
    return a[1];
}
//Time too long
int climbStairs2(int n) {
    if (n <= 3) return n;
    return climbStairs2(n - 1) + climbStairs2(n - 2);
}
//测试,两种方法所耗时间,
int main()
{
    clock_t start_time = clock();
    cout << climbStairs(40) << endl;
    clock_t end_time = clock();
    cout << "Running time :" << (end_time - start_time) << "ms" << endl;
    clock_t start_time1 = clock();
    cout << climbStairs2(40) << endl;
    clock_t end_time1= clock();
    cout << "Running time :" << (end_time1 - start_time1)<< "ms" << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值