动态规划-爬楼梯(leetcode)

1. 题目

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

  • 示例 1:

    输入:n = 2

    输出:2

    解释:有两种方法可以爬到楼顶。

    1 阶 + 1 阶

    2 阶

  • 示例 2:

    输入:n = 3

    输出:3

    解释:有三种方法可以爬到楼顶。

    1 阶 + 1 阶 + 1 阶

    1 阶 + 2 阶

    2 阶 + 1 阶

提示:

1 <= n <= 45

2 思路与编程

当n=1时,f(1) = 1;

当n=2时,f(2) = 2;

当n=3时,f(3) = 3;

当n=4时,f(4) = 5;

当n=5时,f(5) = 8;

所以当n>2时,f(n) = f(n-1) + f(n-2);

c 复制代码
#include <stdio.h>
#include <stdlib.h>

int climbstairs(int n)
{
    if (n == 0) return 0;
    if (n == 1) return 1;
    if (n == 2) return 2;

    return climbstairs(n -1) + climbstairs(n -2);
}

int main()
{
    int n;

    scanf("%d", &n);

    int result = climbstairs(n);

    printf("the result:%d\n", result);

    return 0;
}

运行结果:

c 复制代码
G3-3579:~/data/source/mianshi_code$ gcc climb_stairs.c 
G3-3579:~/data/source/mianshi_code$ ./a.out 
3
the result:3
G3-3579:~/data/source/mianshi_code$ ./a.out 
4
the result:5
G3-3579:~/data/source/mianshi_code$ ./a.out 
5
the result:8
G3-3579:~/data/source/mianshi_code$ ./a.out 
2
the result:2
G3-3579:~/data/source/mianshi_code$ ./a.out 
1
the result:1
G3-3579:~/data/source/mianshi_code$ 
相关推荐
NAGNIP1 天前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队1 天前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶1 天前
算法 --- 字符串
算法
博笙困了1 天前
AcWing学习——差分
c++·算法
NAGNIP1 天前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP1 天前
大模型微调框架之LLaMA Factory
算法
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客1 天前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法