Generate all combinations of well-formed parentheses.

Problem description

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

Examples

1
2
3
4
5
6
7
8
9
10
Example 1:
Input: 3
Output:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

Solution

  和Combinations of a Phone Number类似,都是用回溯法,不过具体运用有些差异。如需要左右指针确定添加左括号还是右括号。先添加左括号深搜下去,直至left == n(PS:左右括号数目均为n),再回溯添加右括号。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 class Solution {
public List<String> generateParenthesis(int n) {
List<String> strings = new ArrayList<>();
group(strings, "", 0, 0, n);
return strings;
}

public void group(List<String> strings, String str, int left, int right, int n) {
if (str.length() == n * 2) {
strings.add(str);
}
if (left < n) {
group(strings, str + '(', left + 1, right, n);
}
if (right < left) {
group(strings, str + ')', left, right + 1, n);
}
}
}
文章目录
  1. 1. Problem description
    1. 1.1. Given n pairs of parentheses(括号), write a function to generate all combinations of well-formed parentheses.
  2. 2. Examples
  3. 3. Solution
  4. 4. Code
|