Leetcode基础刷题之PHP解析(22. Generate Parentheses)

栏目: PHP · 发布时间: 6年前

内容简介:给定一个数字,让我们组合所有()的情况,1就代表一对(),每上一个数就代表就有几对括号。规则是括号一定要匹配。

给定一个数字,让我们组合所有()的情况,1就代表一对(),每上一个数就代表就有几对括号。规则是括号一定要匹配。

每一次可以有两种选择加左括号还是加右括号,但是我们需要注意一个重要规则,如果当前右括号的数等于左括号出现的数,那么不能继续再加右括号了,否则肯定没有与他对应的左括号,递归出口呢?也就是左括号和右括号都用完的时候。

/**
     * @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);
    }

Github整理地址: https://github.com/wuqinqiang/leetcode-php


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Standards Creativity

Web Standards Creativity

Andy Budd、Dan Rubin、Jeff Croft、Cameron Adams、Ethan Marcotte、Andy Clarke、Ian Lloyd、Mark Boulton、Rob Weychert、Simon Collison、Derek Featherstone / friends of ED / March 19, 2007 / $49.99

Book Description * Be inspired by 10 web design lessons from 10 of the world's best web designers * Get creative with cutting-edge XHTML, CSS, and DOM scripting techniques * Learn breathtakin......一起来看看 《Web Standards Creativity》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

html转js在线工具
html转js在线工具

html转js在线工具