leetcode 22. Generate Parentheses

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Example 1:

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:

Input: n = 1
Output: ["()"]

Constraints:

1 <= n <= 8


python 解法

p is the parenthesis-string built so far, left and right tell the number of left and right parentheses still to add, and parens collects the parentheses.

Solution 1

def generateParenthesis(self, n):
    def generate(p, left, right, parens=[]):
        if left:         generate(p + '(', left-1, right)
        if right > left: generate(p + ')', left, right-1)
        if not right:    parens += p,
        return parens
    return generate('', n, n)

Solution 2

Here I wrote an actual Python generator. I allow myself to put the yield q at the end of the line because it’s not that bad and because in “real life” I use Python 3 where I just say yield from generate(…).

def generateParenthesis(self, n):
    def generate(p, left, right):
        if right >= left >= 0:
            if not right:
                yield p
            for q in generate(p + '(', left-1, right): yield q
            for q in generate(p + ')', left, right-1): yield q
    return list(generate('', n, n))

Solution 3

Improved version of this. Parameter open tells the number of “already opened” parentheses, and I continue the recursion as long as I still have to open parentheses (n > 0) and I haven’t made a mistake yet (open >= 0).

def generateParenthesis(self, n, open=0):
    if n > 0 <= open:
        return ['(' + p for p in self.generateParenthesis(n-1, open+1)] + \
               [')' + p for p in self.generateParenthesis(n, open-1)]
    return [')' * open] * (not n)

c++ 解法


class Solution {
public:
    vector<string> ans;
    void f(string s,int open,int close){        //open => '(' count remaining
        if(open==0&&close==0){                  //close=> ')' count remaining
            ans.push_back(s);
            return;
        }
        if(open>0)f(s+"(",open-1,close);
        if(open<close)f(s+")",open,close-1);    //'(' must be placed before ')'
    }
    vector<string> generateParenthesis(int n) {
        ans.clear();
        f("",n,n);                              //Balanced string will have
        return ans;                             //n-open and n-closing brackets
    }
};
shiter CSDN认证博客专家 NLP 自然语言处理 算法
CSDN博客专家,版主,博客累计近300w 人次访问。 熟悉自然语言处理、大数据、数据分析,计算机视觉等领域的研发工作。熟悉Spark\Elasticsearch\Hadoop生态圈,c/c++开发,OpenCV接口。熟悉大数据生态圈下的Python开发。 曾参与并负责国家级大数据安全项目相关POC验证与探索工作。 目前负责大健康平台相关开发与管理工作,Generally speaking I am a hard working man!!!
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: Age of Ai 设计师:meimeiellie 返回首页
实付 29.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值