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

【Leetcode】【Easy】Climbing Stairs

2015-01-14 04:06 387 查看
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?

解题:

简单的运算后,可知此题为斐波那契数列生成题。

解题步骤:

1、新建三个初始变量step1 = 1,step2 = 2,result;

2、注意算法从n = 3开始,所以当n < 3时,直接返回结果。

class Solution {
public:
int climbStairs(int n) {
int result = 0;
int stepOne = 1;
int stepTwo = 2;

if (n == 1 || n == 2)
return n;

while (n-- && n >= 2) {
result = stepOne + stepTwo;
stepOne = stepTwo;
stepTwo = result;
}

return result;
}
};


附录:

斐波那契以及其他有趣数学数列
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: