Title:
You is climbing a stair case. It takes n steps to reach the top.
Each time you can either climb 1 or 2 steps. In what many distinct ways can you climb to the top?
Thinking Analysis:
can not be judged in a sudden fibonacci number, and began to analyze the problem.
the number of solutions for N steps Stair (s[n]) , which can be made up of two parts, s[n-1] && S[n-2], because one or two of the remaining steps can be completed at once (topic requirements). Then there are s[n] = s[n-1] + s[n-2]. This is reminiscent of the Fibonacci sequence:
Mathematically, the faipot sequence is defined in a recursive way:
In words, the faipot sequence starts with 0 and 1, and then the Fibonacci coefficients are added by the previous two numbers. The first few fee Fibonacci coefficients are (? A000045):
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ...
Complexity: O (N)
Attention:
1. Note the number of cycles, N-2 times, and the initial values of Stepone and Steptwo.
2. The subtleties of the algorithm, the spatial complexity is constant, because only two variables are used to hold the values of the first two items, rather than the container vector to preserve the entire value of the sequence.
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 initializes int stepone = 1, steptwo = 1; int ret = 0; Fibonacci number S[n] = s[n-1] + s[n-2]. Stepone is s[n-1], Steptwo is s[n-2], starting with the No. 0 item. Statistics N-2 times. 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;} ;
[C + +] Leetcode:52 Climbing Stairs