LeetCode - Generate Parentheses
Problem description
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:
1
2
3
4
5
6
7
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
Analysis
Basic idea is to use DFS to find all the valid combination.
Here’s the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class GenerateParentheses {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
char[] path = new char[n * 2];
dfs(res, 0, path, 0);
return res;
}
void dfs(List<String> res, int index, char[] path, int value) {
if (value < 0) {
return;
}
if (index == path.length) {
if (value == 0) {
res.add(new String(path));
}
return;
}
path[index] = '(';
dfs(res, index + 1, path, value + 1);
path[index] = ')';
dfs(res, index + 1, path, value - 1);
}
}
value indicate that how many left bracket remain, if value < 0 means it’s not a valid path.