Stair-taking algorithm

Source: Internet
Author: User

First, let's take a look at the following staircase:

Altogether four layers, we stipulated " one person climbs the staircase, one step can take one level, the second level step, if the staircase has n level, asks to write the procedure, asks altogether how many kinds of Go method ", Next we statistics this four layer, each layer's Walk method:

From this short statistic, we can find a law (if it is not seen, can be more than a few stairs), starting from the third ladder, the way is the first step and the second step of the law of the sum, the fourth step is the third ladder and the second step of the law of the sum, so we can get the following formula:

The recursive algorithm is used here.

And the first ladder and the second ladder such an irregular number, we can quantify him, thus, we come to the following implementation of the method to find the steps of the N-step:

function getnum ($n) {    switch($n) {        Case 1:            return 1;          Case 2:            return 2;         default:            return getnum ($n-1) + getnum ($n-2);}    }

If climbing stairs can also step three steps, this time is actually, N-class stair problem can be divided into: N-1 class staircase, N-2 stairs, N-3 stairs of the way of the sum. And so on, but generally it is the biggest three steps.

Stair-taking algorithm

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.