2019-06-04 吴亲库里 库里的深夜食堂
让我们根据电话号码的数字,组合所有情况的字符串,题目给的是23,对应着九种组合。
****
每一次可以有两种选择加左括号还是加右括号,但是我们需要注意一个重要规则,如果当前右括号的数等于左括号出现的数,那么不能继续再加右括号了,否则肯定没有与他对应的左括号,递归出口呢?也就是左括号和右括号都用完的时候。
/**
* @param Integer $n
* @return String[]
*/
function generateParenthesis($n) {
$res=[];
$this->helper($res,"",$n,$n);
return $res;
}
function helper(&$res,$cur,$open,$close){
if($open == 0 && $close ==0) array_push($res,$cur);
if($open>$close) return ;
if($open>0) $this->helper($res,$cur.'(',$open-1,$close);
if($close>0) $this->helper($res,$cur.')',$open,$close-1);
}