动态规划-爬楼梯(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$ 
相关推荐
数研小生42 分钟前
构建命令行单词记忆工具:JSON 词库与艾宾浩斯复习算法的完美结合
算法·json
芒克芒克43 分钟前
LeetCode 题解:除自身以外数组的乘积
算法·leetcode
Python 老手1 小时前
Python while 循环 极简核心讲解
java·python·算法
@Aurora.1 小时前
优选算法【专题九:哈希表】
算法·哈希算法·散列表
爱看科技2 小时前
微美全息(NASDAQ:WIMI)研究拜占庭容错联邦学习算法,数据安全与隐私保护的双重保障
算法
qq_417129252 小时前
C++中的桥接模式变体
开发语言·c++·算法
YuTaoShao2 小时前
【LeetCode 每日一题】3010. 将数组分成最小总代价的子数组 I——(解法二)排序
算法·leetcode·排序算法
吴维炜4 小时前
「Python算法」计费引擎系统SKILL.md
python·算法·agent·skill.md·vb coding
Σίσυφος19005 小时前
PCL Point-to-Point ICP详解
人工智能·算法
玄〤5 小时前
Java 大数据量输入输出优化方案详解:从 Scanner 到手写快读(含漫画解析)
java·开发语言·笔记·算法