-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0022-generate-parentheses.java
42 lines (36 loc) · 1.02 KB
/
0022-generate-parentheses.java
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
package arrays;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Stack;
public class Solution {
public static void main(String[] args) {
Solution sol = new Solution();
sol.generateParenthesis(3);
}
Stack<Character> stack = new Stack<>();
List<String> res = new ArrayList<>();
public List<String> generateParenthesis(int n) {
backtrack(0, 0, n);
return res;
}
private void backtrack(int openN, int closedN, int n) {
if (openN == closedN && closedN == n) {
StringBuilder sb = new StringBuilder();
for (Character c: stack) {
sb.append(c);
}
res.add(sb.toString());
}
if (openN < n) {
stack.push('(');
backtrack(openN + 1, closedN, n);
stack.pop();
}
if (closedN < openN) {
stack.push(')');
backtrack(openN, closedN + 1, n);
stack.pop();
}
}
}