LeetCode 70 Climbing Stairs (crawling Stairs) (Dynamic Planning )(*)
Translation
You are crawling a stair. It takes n steps to reach the top. You can crawl one or two steps each time. How many different methods do you have to climb to the top?
Original
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?
Analysis
To dynamically plan the basic questions, first set three variables for conversion:
int dp1 = 1, dp2 = 2, dpWay = 0;
According to the question, only one or two steps are allowed at a time. Therefore, when n is equal to 2, there are two steps: 1 + 1, 2.
if (n <= 1) return dp1;if (n == 2) return dp2;
Starting from 3, because you can directly obtain the result of its steps, you can directly write it:
while ((n--)-2) {}
The final change is as follows:
dpWay = dp1 + dp2;dp1 = dp2;dp2 = dpWay;
int climbStairsIter(int n, int dpWay,int dp1, int dp2) { if (n <= 1) return dp1; if (n == 2) return dp2; if ((n--) - 2) { dpWay = dp1 + dp2; dp1 = dp2; dp2 = dpWay; return climbStairsIter(n, dpWay, dp1, dp2); } else return dpWay;}int climbStairs(int n) { return climbStairsIter(n, 0,1,2);}
Because the parameters here involve the execution of the preceding sequence, it is better to list them separately, but this seems a little less concise.
Code
class Solution {public: int climbStairs(int n) { int dp1 = 1, dp2 = 2, dpWay = 0; if (n <= 1) return dp1; if (n == 2) return dp2; while ((n--) - 2) { dpWay = dp1 + dp2; dp1 = dp2; dp2 = dpWay; } return dpWay; }};