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

# 22 Generate Parentheses

## 22. [Generate Parentheses](https://leetcode.com/problems/generate-parentheses/description/)

## 1. Question

Givennpairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, givenn= 3, a solution set is:

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

## 2. Implementation

**(1) Backtracking**

```java
class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        StringBuilder paren = new StringBuilder();
        getParenthesis(0, 0, n, paren, res);
        return res;
    }

    public void getParenthesis(int left, int right, int n, StringBuilder paren, List<String> res) {
        if (paren.length() == 2 * n) {
            res.add(paren.toString());
            return;
        }

        if (left < n) {
            paren.append('(');
            getParenthesis(left + 1, right, n, paren, res);
            paren.setLength(paren.length() - 1);
        }

        if (right < left) {
            paren.append(')');
            getParenthesis(left, right + 1, n, paren, res);
            paren.setLength(paren.length() - 1);
        }
    }
}
```

## 3. Time & Space Complexity

**Backtracking:** 时间复杂度O(2^n), 空间复杂度O(2^n)


---

# 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:

```
GET https://protegejj.gitbook.io/algorithm-practice/leetcode/backtracking/22-generate-parentheses.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
