LeetCode 0022 - Generate Parentheses

2021-08-11 10:19:53 浏览数 (1)

Generate Parentheses

Desicription

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

For example, given n = 3, a solution set is:

代码语言:javascript复制
[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

Solution

代码语言:javascript复制
class Solution {
public:
    vector<string> res;
    vector<string> generateParenthesis(int n) {
        addPair("", n, 0);
        return res;
    }
private:
    void addPair(string str, int n, int m){
        if(!n && !m){
            res.push_back(str);
            return ;
        }
        if(m)
            addPair(str ')', n, m-1);
        if(n)
            addPair(str '(', n-1, m 1);
    }
};

0 人点赞