LeetCode 70 Climbing Stairs(记忆化搜索)

来源:互联网 发布:广州980数控编程视频 编辑:程序博客网 时间:2024/06/06 11:47

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阶楼梯的方法数,那么有以下状态转移方程:

    n == 1时,step[n] = 1

    n == 2时,step[n] = 2

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

代码如下:

#define maxn 105int step[maxn];int climbStairs(int n) {    if(step[n]) return step[n];    if(n == 1 || n == 2) step[n] = n;    else step[n] = climbStairs(n - 1) + climbStairs(n - 2);    return step[n];}

0 0