LeetCode——Generate Parentheses

1. Question

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:

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

2. Solution

  1. 用两个数值n和m分别表示需要添加左括号的数目和右括号的数目,直到n和m的数目为0。

  2. 添加一个左括号,意味着需要添加一个右括号。

3. Code

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        string str = "";
        // 左括号的数目决定右括号的数目
        geneCore(res, str, n, 0);
        return res;
    }
    void geneCore(vector<string>& res, string str, int n, int m) {
        if (n == 0 && m == 0) {
            res.push_back(str);
            return;
        }
        if (m > 0) geneCore(res, str + ")", n, m - 1);       // 添加右括号,不影响左括号的数目
        if (n > 0) geneCore(res, str + "(", n - 1, m + 1);   // 添加一个左括号,意味着需要添加一个右括号
    }
};
原文地址:https://www.cnblogs.com/zhonghuasong/p/7798345.html