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


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

查看所有标签

猜你喜欢:

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

Blog Design Solutions

Blog Design Solutions

Richard Rutter、Andy Budd、Simon Collison、Chris J Davis、Michael Heilemann、Phil Sherry、David Powers、John Oxton / friendsofED / 2006-2-16 / USD 39.99

Blogging has moved rapidly from being a craze to become a core feature of the Internetfrom individuals sharing their thoughts with the world via online diaries, through fans talking about their favori......一起来看看 《Blog Design Solutions》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具