热门IT资讯网

斐波那契数列(fabnacci)j递归

发表于:2024-11-26 作者:热门IT资讯网编辑
编辑最后更新 2024年11月26日,

//$all为1则返回fabnacci数列所有数组元素
function fabnacci($n, $all = 1){

static $fabn = [];if($n < 2){    $fabn[$n] = 1;      }else{    if(empty($fabn[$n])){        $fabn[$n] = fabnacci($n - 1, 0) + fabnacci($n - 2, 0);    }}if($all == 1){    return $fabn;}else{    return $fabn[$n];}   

}

var_dump(implode(" ", fabnacci(10)));
var_dump(implode(" ", fabnacci(10)));
?>
返回显示
string(26) "1 1 2 3 5 8 13 21 34 55 89" string(26) "1 1 2 3 5 8 13 21 34 55 89"

0