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.