Several steps to the stairs

Source: Internet
Author: User
Assume that a stair has N steps, and a person can span up to M steps at a time. For example, there are a total of three steps for a person to take two steps at a time. that is to say, a person can take one or two steps at a time, but there are no more than two steps, there are three steps to the stairs. It is now required to use a program to calculate the total number of steps. It is actually a Fibonacci series.

Assume that a stair has N steps, and a person can span up to M steps at a time. For example, there are a total of three steps for a person to take two steps at a time. that is to say, a person can take one or two steps at a time, but there are no more than two steps, there are several steps to the stairs:

    ①:1 1 1②:1 2③:2 1

It is now required to use a program to calculate the total number of steps.

It is actually a Fibonacci series. The following is a recursive solution:

 ';}?>

Program running result:

1235813213455

Non-recursive method:

function up($n){$a = array(1, 2);for($i = 3; $i <= $n; $i++){$a[$i] = $a[$i-1] + $a[$i-2];}print_r($a);}up(10);

If we want to show all the situations in a recursive method:

function up_out($n){if($n == 1)return array('1 ');else if($n == 2)return array('1 1 ', '2 ');return array_merge(lian(up_out($n-1),'1 '), lian(up_out($n-2), '2 '));}function lian($a1, $a2){foreach($a1 as &$a1_v) {$a1_v = $a1_v . $a2;}return $a1;}print_r(up_out(10));

Non-recursive methods that show all situations:

function up_out($n){$re = array(array(0), array('1 '), array('1 1 ', '2 '));for($i = 3; $i <= $n; $i++) {$re[$i] = array_merge(lian($re[$i-1], '1 '), lian($re[$i-2], '2 '));}return $re;}function lian($a1, $a2) {foreach($a1 as &$a_v) {$a_v = $a_v . $a2;}return $a1;}print_r(up_out(10));

This article is available at http://www.nowamagic.net/librarys/veda/detail/995.

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.