如何使此功能与递归一起使用?

时间:2015-03-29 17:14:18

标签: php recursion

输出:

3
3 4
3 4 5
3 4 5 6
3 4 5 6 7
3 4 5 6 7 8
function Triangle ($begin, $end) {
    if ($begin < 0 || $end < 0) {
        return;
    }
    if ($begin == $end) {
        return $a;
    }
    else {
        // non recursive
        for ($i = 1; $i <= $end; $i++) {
            for ($j = $begin; $j <= $i; $j++) {

                echo $j . " ";
            }
            echo "<br>";
        }
    }
}

这是我到目前为止所做的。

2 个答案:

答案 0 :(得分:2)

这是一种方式:

function triangle ($begin, $end, $row = 1) {
    //stop when we've printed up to end
    if($end - $begin + 1 < $row) return;

    //let's start at the beginning :)
    for($i = 0; $i < $row; $i++){
        //the row number increments each time so we can keep adding.
        echo ($begin + $i)." ";
    }
    echo "<br>";
    //now recurse...
    triangle($begin, $end, $row + 1);
}

用法:

triangle(3,9);

输出:

3 
3 4 
3 4 5 
3 4 5 6 
3 4 5 6 7 
3 4 5 6 7 8 
3 4 5 6 7 8 9

答案 1 :(得分:1)

这应该适合你:

(这里我添加了变量步骤,它定义了从$begin$end以及$begin + $step == $end的步数功能完成。如果不是它从$begin开始并进行X步骤,只要它没有到达结束,我再用一步再调用该函数)

<?php

    function Triangle($begin, $end, $step = 0) {

        for($count = $begin; $count <= ($begin+$step); $count++)
            echo "$count ";
        echo "<br />";

        if(($begin + $step) == $end)
            return;
        else
            Triangle($begin, $end, ++$step);

    }

    Triangle(3, 8);

?>

输出:

3 
3 4 
3 4 5 
3 4 5 6 
3 4 5 6 7 
3 4 5 6 7 8