题目:
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<=2 时 返回的n, 当n>2 时
s[n]=s[n-1]+s[n-2]; 因为第一步可能走一个台阶 第一步也可能走两个台阶
所以这里可以仅仅使用两个变量来记录
int Climbing_num(int n)
{
int first =1;
int second =2;
int sum = 0;
int i;
if(n<=2)
return n;
else
for(i=3;i<=n;i++)
{
sum = first+second;
first = second ;
second = sum;
}
return sum;
}
int main()
{
cout<<Climbing_num(25)<<endl;
return 0;
}
当然也可以不用first和second,而是使用申请空间,但是这样的话会浪费空间复杂度