题目链接:https://leetcode.com/problems/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?
Subscribe to see which companies asked this question
两种方法,循环和递归,递归超时(功能正确)
代码1:循环
class Solution {
public:
int climbStairs(int n) {
if(n==1||n==2)
return n;
int fn_1=2;
int fn_2=1;
int tmp;
for(int i=3;i<=n;i++)
{
tmp=fn_1+fn_2;
fn_2=fn_1;
fn_1=tmp;
}
return tmp;
}
};
代码2:递归
class Solution {
public:
int climbStairs(int n) {
return climb(n);
}
int climb(int n)
{
int re;
if(n==1||n==2)
return n;
re=climb(n-1)+climb(n-2);
return re;
}
};