您的位置:首页 > 大数据 > 人工智能

LeetCode 70 Climbing Stairs(记忆化搜索)

2017-05-13 13:09 405 查看
You are climbing a stair case. It takes n steps to reach to the top.

Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Note: Given n will be a positive integer.

题目大意:有N阶楼梯,每次可以选择上一阶或两阶,问从第一阶上到第N阶有多少种方法。

解题思路:令step
为上到第N阶楼梯的方法数,那么有以下状态转移方程:

    n == 1时,step
= 1

    n == 2时,step
= 2

    n > 2时,step
= step[n - 1] + step[n - 2]

代码如下:

#define maxn 105

int step[maxn];

int climbStairs(int n) {
if(step
) return step
;
if(n == 1 || n == 2) step
= n;
else step
= climbStairs(n - 1) + climbStairs(n - 2);
return step
;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode