用 PHP 来刷leetCode 之 括号生成

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 = 3,生成结果为:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

 

class Solution {
    public $arr=[];
    /**
     * @param Integer $n
     * @return String[]
     */
    function generateParenthesis($n) {
        $this->handle("",0,0,$n);
        return $this->arr;
    }
    function handle($str,$left,$right,$n){
        if($left==$n && $right==$n){
            $this->arr[] = $str;
            return ;
        }
        if ($left<$n){
            $this->handle($str."(",$left+1,$right,$n);
        }
        if ($right<$left){
            $this->handle($str.")",$left,$right+1,$n);
        }
        
        
    }
}

用 PHP 来刷leetCode 之 括号生成