题目:
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?
无法一下子判断是 Fibonacci number,于是开始分析问题。
the number of solutions for N steps stair(S[N]),可以由两部分组成,S[N-1] && S[N-2],由于剩下一步或者两步可以一次完成(题目要求)。则有S[N]
= S[N-1] + S[N-2]。 由此联想到斐波那契数列:
- (n≧2)
用文字来说,就是费波那契数列由0和1开始,之后的费波那契系数就由之前的两数相加。首几个费波那契系数是(?A000045):
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233……
复杂度:O(N)
Attention:
1.注意循环的次数,N-2次;还有stepOne和stepTwo的初始值。
2.算法的精妙处,空间复杂度为常数,因为只使用了两个变量保存前两项的值,而不是用容器vector保存数列的全部值。
ret = stepOne + stepTwo; //S[N] = S[N-1] + S[N-2]
stepTwo = stepOne; //S[N-1]_new = S[N-2]_old
stepOne = ret; //S[N-2]_new = S[N]_old
AC Code:
class Solution { public: int climbStairs(int n) { if(n == 0 || n == 1) return 1; //Fibonacci number 初始化 int stepOne = 1, stepTwo = 1; int ret = 0; //Fibonacci number S[N] = S[N-1] + S[N-2]. stepOne计为S[N-1], stepTwo计为S[N-2],从第0项开始。统计N-2次。 for(int i = 2; i <= n; i++) { ret = stepOne + stepTwo; //S[N] = S[N-1] + S[N-2] stepTwo = stepOne; //S[N-1]_new = S[N-2]_old stepOne = ret; //S[N-2]_new = S[N]_old } return ret; } };
时间: 2024-10-04 07:10:33