题目描述
Climbing Stairs
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的方法数为f(n),我们只考虑最后一次,最后一次可能是爬一阶到n阶,也可以是从n-2爬两阶到达。
那么容易选出
f(n) = f(n-1)+f(n-2)
好了,剩下就是典型的费波那契数列问题。
这里不要直接使用递归,因为递归里面有重复计算,如在算f5,和f4时都要计算一次f3.
需要优化一下。
代码示例
#include <iostream>
using namespace std;
class Solution {
public:
int climbStairs(int n) {
if(n < 3) return n;
int ret = 0;
int one = 1;
int two = 2;
for(int i = 3;i<=n;i++)
{
ret = two;
two = one + two;
one = ret;
}
ret = two;
return ret;
}
};
void test0(int x,int expect)
{
Solution so;
int ret = so.climbStairs(x);
if(ret != expect)
printf("------------------------failed\n");
else
printf("------------------------passed\n");
}
int main()
{
test0(5,8);
return 0;
}
#include <iostream>
using namespace std;
class Solution {
public:
int climbStairs(int n) {
if(n < 3) return n;
int ret = 0;
int one = 1;
int two = 2;
for(int i = 3;i<=n;i++)
{
ret = two;
two = one + two;
one = ret;
}
ret = two;
return ret;
}
};
void test0(int x,int expect)
{
Solution so;
int ret = so.climbStairs(x);
if(ret != expect)
printf("------------------------failed\n");
else
printf("------------------------passed\n");
}
int main()
{
test0(5,8);
return 0;
}
推荐学习C++的资料
C++标准函数库
在线C++API查询