I. Question
There are n steps to climb the stairs. Each time you can climb the level 1 or Level 2, how many crawling methods do you climb to the top?
Ii. Analysis
If F (n) is set, it indicates the number of different methods used to climb the n-level stair. to climb the n-level stair, there are two options:
1. Step forward from n-1
2. Two steps forward from The N-2 order
So there is, F (n) = f (n-1) + f (n-2) Isn't that the Fibonacci series?
Therefore,
Method 1: Iteration
Method 2: Recursion
Method 3: formula F (n) = (1/√ 5) * {[(1 + √ 5)/2] ^ N-[(1-√ 5) /2] ^ n}
Class solution {public: int climbstairs (int n) {int flag; int stair0 = 1; int stair1 = 1; if (n <= 0) return 0; if (n = 1) return 1; for (INT I = 2; I <= N; I ++) {flag = stair1; stair1 = stair0 + stair1; stair0 = flag;} return stair1 ;}}; formula: Class solution {public: int climbstairs (int n) {double flag = SQRT (5 ); return floor (POW (1 + flag)/2, n + 1) + POW (1-flag)/2, n + 1 )) /flag + 0.5 );}};
Leetcode: climbing_stairs