算法 - 递归 - 算法综合

<?php
header("Content-type: text/html; charset=utf-8");

/**
 * +-----------------
 * | 阶乘
 * +-----------------
 */
function factorial( $n ) {
    if ( 1 == $n ) return 1;
    $result = $n * factorial( $n - 1 );
    return $result;
}
//echo factorial( 5 );



/**
 * +-----------------
 * 斐波那契数列
 * +-----------------
 */
function fibonacci( $n ) {
    if ( 1 == $n || 2 == $n ) return 1;
    $result = fibonacci( $n - 1 ) + fibonacci( $n - 2 );
    return $result;
}
//echo fibonacci( 6 );



/**
 * +-----------------
 * 汉诺塔
 * +-----------------
 */
function hanoi( $n, $from, $depend, $to ) {
    if( 1 == $n ) {
        move( $n, $from, $to );
    } else {
        hanoi( $n - 1, $from, $to, $depend);
        move( $n, $from, $to );
        hanoi( $n - 1, $depend, $from, $to );
    }
}
#将第$n个圆盘,从$from柱子,移动到$to柱子
function move( $n, $from, $to ) {
    echo '将' . $n . '号盘,从' . $from . '移动到' . $to . '<br/>';
}
//hanoi( 3, 'A', 'B', 'C' );

 

posted on 2016-03-23 17:38  ultrastrong  阅读(155)  评论(0编辑  收藏  举报