Skip to content

Latest commit

 

History

History
46 lines (37 loc) · 1.57 KB

22.md

File metadata and controls

46 lines (37 loc) · 1.57 KB

✏️Leetcode之PHP版题目解析(22. Generate Parentheses)

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);
      }

联系