LeetCode 70 Climbing Stairs (crawling Stairs) (Dynamic Planning )(*)

Source: Internet
Author: User

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;    }};
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.