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

LeetCode解题报告 70. Climbing Stairs [easy]

2016-10-21 11:52 549 查看

题目描述

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?

解题思路

题目意思很好理解,一次只能上一个或者两个台阶,到达第n个台阶共有多少种方法?
到达第n个台阶只有两种方法,从第n-1个台阶走一步上来,或者从第n-2个台阶走两步上来,这样第n个台阶的方法数就是第n-1个台阶的方法数加上第n-2个台阶的方法数。
用递归的方法会超时,这里用动态规划,时间复杂度是O(n)的。

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