使用动态规划,我们可以知道,当爬第n层时候,因为一次只能爬两格或者一格,因此f(n)=f(n-1)+f(n-2)。
写法一:
递归,时间会超出限制,但是使用别的编译器,返回结果是正确的。
class Solution {
public:
int climbStairs(int n) {
int result = 0;
if(n==0||n==1)
return 1;
result = climbStairs(n-1)+climbStairs(n-2);
return result;
}
};
写法二:
非递归。
class Solution {
public:
int climbStairs(int n) {
if(n==1||n==0)
return 1;
int n_1 = 1;
int n_2 = 1;
int result = 0;
for(int i =2;i<=n;i++)
{
result = n_1+n_2;
n_2 =n_1 ;
n_1 = result;
}
return result;
}
};