动态规划-爬楼梯(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$ 
相关推荐
秋说40 分钟前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy1 小时前
力扣61.旋转链表
算法·leetcode·链表
卡卡卡卡罗特3 小时前
每日mysql
数据结构·算法
chao_7893 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
lifallen4 小时前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法
lixzest4 小时前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
EndingCoder4 小时前
搜索算法在前端的实践
前端·算法·性能优化·状态模式·搜索算法
丶小鱼丶4 小时前
链表算法之【合并两个有序链表】
java·算法·链表
不吃洋葱.5 小时前
前缀和|差分
数据结构·算法
是白可可呀7 小时前
LeetCode 169. 多数元素
leetcode