递归与迭代

1.Fibonacci (递归法)


<?php 
$n = $_GET['n'];
function fac($n) {
	if($n == 0 || $n == 1) {
		return $n;
	}
	if($n>1) {
		return (fac($n-1) + fac($n-2));
	}
	
}
echo $fac = fac($n);
?>


  斐波那契(迭代法)

  参考:http://blog.csdn.net/a9529lty/article/details/4564758

<?php
/**
* fibonacci iteration
*  
*/

$n = $_GET['n'];

$fibonacci0 = 0;
$fibonacci1 = 1;
if($n == 0){
	$fibonacci = $fibonacci0;
}
else if($n == 1){
	$fibonacci = $fibonacci1;
}
for($i = 2;$i <= $n;$i ++ ){	
	$fibonacci = $fibonacci0 + $fibonacci1;
	$fibonacci0 = $fibonacci1;
	$fibonacci1 = $fibonacci;
}

echo $fibonacci;
	
?>


2.阶乘(递归法)

<?php
$n = $_GET['n'];

function factorial($n) {
	if($n == 0){
		return 1;
	}
	else{
		return $n * factorial($n-1);
	}
}

echo $factorial = factorial($n);
?>

  阶乘(迭代法)

<?php
/**
* factorail iteration
*  
*/

$n = $_GET['n'];
$factorial = 1;

for($i = 0;$i <= $n;$i ++){
	if($i == 0) {
		continue;
	}
	$factorial = $factorial * $i;
}
echo $factorial;
?>




3.hanoi 塔


参考:http://www.luocong.com/dsaanotes/index-Z-H-8.htm#node_sec_7.2.3

           http://zh.wikipedia.org/wiki/%E6%B1%89%E8%AF%BA%E5%A1%94

<?php 
$n = $_GET['n'];

$source = "A";
$auxiliary = "B";
$destination ="C";

function hanoi($n,$source,$auxiliary,$destination) {
	if($n == 1) {
		echo "Move disk $n $source --> $destination";
		echo "<br />";
	}
	else{		
		hanoi($n-1, $source,$destination,$auxiliary);
		echo "Move  disk $n $source --> $destination";
		echo "<br />";
		hanoi($n-1, $auxiliary,$source,$destination);
	}
}

hanoi($n, $source, $auxiliary, $destination);

Tower of Hanoi 迭代法(还不会现在)

note:1How does this iterative Tower of Hanoi work? C [duplicate]

          2.http://phoxis.org/2012/05/01/towers-of-hanoi-iterative-process-simulating-recursion/
 


4.杨辉三角(pascal's triangle)



 
 

<?php
/**
 * Pascal's triangle
 * */
$n = $_GET['n'];

for($row = 1;$row <= $n;$row ++){
	//打印每行前面的空格
	for($col = 1;$col <= ($n-$row);$col ++){
		echo " ";
	}
	for($col = 1;$col <=$row;$col ++){
		echo $triangle_row = print_triangle($row,$col);
		echo "\t";	
	}
	echo "<br />";
}

function print_triangle($row,$col) {
	if($col == 1 || $col == $row){
		return 1;
	}
	else{
		return print_triangle($row-1, $col-1)+print_triangle($row-1, $col);
	}
}
?>



你可能感兴趣的:(递归与迭代)