动态规划-爬楼梯(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$ 
相关推荐
Wendy14417 小时前
【线性回归(最小二乘法MSE)】——机器学习
算法·机器学习·线性回归
拾光拾趣录7 小时前
括号生成算法
前端·算法
渣呵8 小时前
求不重叠区间总和最大值
算法
拾光拾趣录8 小时前
链表合并:双指针与递归
前端·javascript·算法
好易学·数据结构8 小时前
可视化图解算法56:岛屿数量
数据结构·算法·leetcode·力扣·回溯·牛客网
香蕉可乐荷包蛋9 小时前
AI算法之图像识别与分类
人工智能·学习·算法
chuxinweihui10 小时前
stack,queue,priority_queue的模拟实现及常用接口
算法
tomato0910 小时前
河南萌新联赛2025第(一)场:河南工业大学(补题)
c++·算法
墨染点香10 小时前
LeetCode Hot100【5. 最长回文子串】
算法·leetcode·职场和发展
人肉推土机10 小时前
Planning Agent:基于大模型的动态规划与ReAct机制,实现复杂问题自适应执行求解
大模型·动态规划·react·planning agent