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?
解题思路:这是一个裴波那契数列。
java版本:
public class Solution {
public int climbStairs(int n) {
if(n<=2) return n;
int i=3;
int s1=1,s2=2,s=0;
while(++i<=n){
s=s1+s2;
s1=s2;
s2=s;
}
return s;
}
}
c++版本:
class Solution {
public:
int climbStairs(int n) {
int step1=1,step2=2,step=0;
if(n<=2) return n;
int i=3;
while(++i<=n){
step=step1+step2;
step1=step2;
step2=step;
}
return step;
}
};
本文详细介绍了如何通过裴波那契数列解决爬楼梯问题,提供了Java和C++版本的代码实现,适用于计算机科学领域的算法学习。
1563

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



