开发者

Generate all binary strings of length n

<?php
    $n = 3;
    $x = array();
    function Try1($i){
        foreach(array(0,1)开发者_JAVA百科 as $j){
            $x[$i] = $j;
            if($i==$n-1){
                print_r($x);
            }else{
                Try1($i+1);
            }
        }
    }

    Try1(0);
?>

I wrote a piece of code above, but when I ran I got an error: Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 24 bytes) in BinaryStrings.php on line 5.

I wrote a similar version in python and it work, can you help me? Thank you ^^.


The variables $x and $n are not in the same scope as the rest of your code. They're defined outside the function and not passed into it, so they don't exist inside the function. $n-1 inside the function hence equals -1 and your code will run into an endless loop. That's why you a) turn on error reporting and b) use conditions with < or >, not ==.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜