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

LeetCode -- 70. Climbing Stairs

2017-05-17 11:15 239 查看

题目:

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.

思路:

这道题很简单,最简单的动态规划,也是一个斐波那契数列。

定义
d[i]
为i阶楼梯的方法数,那么到达第i阶楼梯只有两种方法,从i-1阶楼梯上一个台阶,从i-2个台阶上两个楼梯。

初始状态:

d[0]=d[1]=1;

状态转移方程:

d[i]=d[i−1]+d[i−2],i>=2;

C++代码:

class Solution {
public:
int climbStairs(int n) {
int d[100];
d[0]=1, d[1]=1;
for(int i=2;i<=n;i++)
{
d[i] = d[i-1]+d[i-2];
}
return d
;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c-c++