题目描述
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查询
爬楼梯问题与斐波那契数列
本文探讨了经典的爬楼梯问题,通过分析得出每次可以爬1阶或2阶的情况下,到达第n阶的不同方式数量。文章提供了一种避免重复计算的优化算法,并附带C++代码实现。
484

被折叠的 条评论
为什么被折叠?



