> For the complete documentation index, see [llms.txt](https://wentao-shao.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://wentao-shao.gitbook.io/leetcode/graph-search/22.generate-parentheses.md).

# 22.Generate-Parentheses

## 22. Generate Parentheses

## 题目地址

<https://leetcode.com/problems/generate-parentheses/>

## 题目描述

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

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

## 代码

### Approach 1: Brute Force

```java
class Solution {
  public List<String> generateParenthesis(int n) {
        List<String> combinations = new ArrayList();
    generateAll(new char[2 * n], 0, combinations);
    return combinations;
  }

  private void generateAll(char[] current, int pos, List<String> result) {
    if (pos == current.length) {
        if (valid(current)) {
          result.add(new String(current));
        }
      } else {
      /// looks like backtrace
        current[pos] = '(';
        generateAll(current, pos + 1, result);
        current[pos] = ')';
        generateAll(current, pos + 1, result);
      }
    }

    private boolean valid(char[] current) {
      int balance = 0;
      for (char c : current) {
        if (c == '(') {
          balance++;
        } else {
          balance--;
        }
        if (balance < 0)    return false;
      }

      return (balance == 0);
    }

}
```

### Approach #2 Backtracking

```java
class Solution {
  public List<String> generateParenthesis(int n) {
    List<String> ans = new ArrayList();
    backtrack(ans, "", 0, 0, n);
    return ans;
  }

  public void backtrack(List<String> ans, String cur, int open, int close, int max) {
    if (cur.length() == max * 2) {
      ans.add(cur);
      return;
    }

    if (open < max) {
      backtrack(ans, cur + "(", open + 1, close, max);
    }

    if (close < open) {
      backtrack(ans, cur + ")", open, close + 1, max);
    }

  }

}
```

### Approach #3 Closure Number

```java
class Solution {
  public List<String> generateParenthesis(int n) {
    List<String> ans = new ArrayList();
    if (n == 0) {
      ans.add("");
    } else {
      for (int c = 0; c < n; c++) {
        for (String left: generateParenthesis(c)) {
          for (String right: generateParenthesis(n - 1- c)) {
            ans.add("(" + left + ")" + right);
          }
        }
      }
    }
    return ans;
  }
}
```


---

# 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://wentao-shao.gitbook.io/leetcode/graph-search/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.
