LeetCode:括号生成

https://leetcode-cn.com/problems/generate-parentheses/

class Solution {

    /**
     * @param Integer $n
     * @return String[]
     */
    function generateParenthesis($n) {
        $res = [];
        $this->dfs($res,0, 0, '', $n);
        return $res;
    }
    //整体思路点:
    //1、左边和右边括号数不可以大于n
    //2、左边在任何情况下都必须大于等于右边
    private function dfs(&$res, $left, $right, $tmp, $n)
    {
        if ($left == $n && $right == $n){
            $res[] = $tmp;
            return;
        }
        //左边只要小于n时就可以加左括号,因为右边可以任意闭合
        if ($left < $n){
            $this->dfs($res,$left + 1, $right, $tmp . '(', $n);
        }
        //右边小于n且左边大于右边时,才允许加右括号
        //左边小于右边不可以加右括号,否则会多出来左括号无法闭合
        if ($left > $right && $right < $n){
            $this->dfs($res, $left, $right + 1, $tmp . ')', $n);
        }
    }
}
发布了218 篇原创文章 · 获赞 29 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/why444216978/article/details/104445218