-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path22_generate_parentheses.java
More file actions
42 lines (34 loc) · 931 Bytes
/
22_generate_parentheses.java
File metadata and controls
42 lines (34 loc) · 931 Bytes
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
32
33
34
35
36
37
38
39
40
41
42
/*
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
*/
class Solution {
List<String> res;
public List<String> generateParenthesis(int n) {
res = new ArrayList<String>();
if (n <= 0) {
return res;
}
backtracking("", 0, 0, n);
return res;
}
private void backtracking(String buffer, int open, int close, int limit) {
if (open + close == limit * 2) {
res.add(buffer.toString());
return;
}
if (open < limit) {
backtracking(buffer + "(", open + 1, close, limit);
}
if (close < open) {
backtracking(buffer + ")", open, close + 1, limit);
}
}
}