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

动态规划——70. Climbing Stairs[easy]

2017-05-07 00:10 274 查看
题目描述

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.
爬楼梯,一次只能爬1步或2步,问到顶n有多少种走法

解题思路

a-b-c-d-e

假设有如上的楼梯,为了走到e,我倒数第二步应该在c或者d。令ways表示到当前步的方法总数,那么,ways[n]= ways[n-1]+ways[n-2]。n-2走2步到n,或者n-1走1步到n。

我一开始有一个疑问:c走一步到d,那么ways[c]+ways[d]会不会有重复呢?答案是否定的,c走一步到d,那么这一种走法应当算到ways[d]里了。n-2的意思是,一次走2步到达n的方法,n-1是一次走一步到达n的走法。(可能我的解释还是不太清楚,读者用0,1,2三个数来走一遍接下来的算法应该就明白了)

代码如下

class Solution {
public:
int climbStairs(int n) {
if (n == 0)
return 1;
if (n == 1)
return 1;
vector<int> re(n, 0);
re[0] = 1;
re[1] = 1;

for (int i = 2; i < n; i++)
re[i] = re[i - 1] + re[i - 2];

return re[n - 1]+re[n-2];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  动态规划