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比较大的话内存爆了那是妥妥的。
就按照 f(n) = f(n-1) + f(n-2)
来计算。
递归
int fibolaci(int a,int b,int i,int n)
{
if(i>n)
{
return b;
}
return fibolaci(b,a+b,i+1,n);
}
int climbStairs(int n) {
return fibolaci(0,1,1,n);
}
o(n) + o(1)
int climbStairs(int n) {
int pre = 1;
int cur = 1;
int step = 1;
int temp ;
while(step<n)
{
temp = cur;
cur = cur + pre;
pre = temp;
step++;
}
return cur;
}