LeetCode题目-22

首页 编程分享 LEET_CODE 正文

leetCode 转载 编程分享 2024-12-16 19:41:15

简介 LeetCode题目-22


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


✏描述

让我们根据电话号码的数字,组合所有情况的字符串,题目给的是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);
      }

转载链接:https://leetcode.cn/


Tags:


本篇评论 —— 揽流光,涤眉霜,清露烈酒一口话苍茫。


    声明:参照站内规则,不文明言论将会删除,谢谢合作。


      最新评论




ABOUT ME

Blogger:袅袅牧童 | Arkin

Ido:PHP攻城狮

WeChat:nnmutong

Email:nnmutong@icloud.com

标签云