> For the complete documentation index, see [llms.txt](https://dfine.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dfine.gitbook.io/leetcode/22.generate_parentheses.md).

# 22.Generate Parentheses

**22.Generate Parentheses**

难度:Medium

> 给出 n 代表生成括号的对数，请你写出一个函数，使其能够生成所有可能的并且有效的括号组合。

例如，给出 n = 3，生成结果为：

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

动态规划，可以将已有的有效括号分成左右两部分有效括号，然后在左右分别插入左右括号。这样可以生成下一个长度的有效括号对。

```
class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> res;
        if(n ==0) res.push_back("");
        else
        {
            for(int i=0;i<n;i++)
            for(auto left: generateParenthesis(i))
            for(auto right: generateParenthesis(n-i-1))
            res.push_back( '('  +left+ ')' + right );
        }
        return res;
    }
};
```

> 执行用时 :12 ms, 在所有 C++ 提交中击败了60.89%的用户\
> 内存消耗 :15.4 MB, 在所有 C++ 提交中击败了84.63%的用户


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://dfine.gitbook.io/leetcode/22.generate_parentheses.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
