动态规划-爬楼梯(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$ 
相关推荐
AI小白的Python之路10 分钟前
数据结构与算法-排序
数据结构·算法·排序算法
DashVector20 分钟前
如何通过Java SDK检索Doc
后端·算法·架构
zzz93327 分钟前
transformer实战——mask
算法
一只鱼^_1 小时前
牛客周赛 Round 105
数据结构·c++·算法·均值算法·逻辑回归·动态规划·启发式算法
是阿建吖!1 小时前
【动态规划】斐波那契数列模型
算法·动态规划
啊阿狸不会拉杆1 小时前
《算法导论》第 27 章 - 多线程算法
java·jvm·c++·算法·图论
火车叨位去19492 小时前
力扣top100(day04-05)--堆
算法·leetcode·职场和发展
数据智能老司机2 小时前
面向企业的图学习扩展——面向图的传统机器学习
算法·机器学习
类球状2 小时前
顺序表 —— OJ题
算法
Miraitowa_cheems2 小时前
LeetCode算法日记 - Day 11: 寻找峰值、山脉数组的峰顶索引
java·算法·leetcode