forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0022-generate-parentheses.java
43 lines (37 loc) · 1.04 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
43
packagearrays;
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Stack;
publicclassSolution {
publicstaticvoidmain(String[] args) {
Solutionsol = newSolution();
sol.generateParenthesis(3);
}
Stack<Character> stack = newStack<>();
List<String> res = newArrayList<>();
publicList<String> generateParenthesis(intn) {
backtrack(0, 0, n);
returnres;
}
privatevoidbacktrack(intopenN, intclosedN, intn) {
if (openN == closedN && closedN == n) {
Iteratorvale = stack.iterator();
Stringtemp = "";
while (vale.hasNext()) {
temp = temp + vale.next();
}
res.add(temp);
}
if (openN < n) {
stack.push('(');
backtrack(openN + 1, closedN, n);
stack.pop();
}
if (closedN < openN) {
stack.push(')');
backtrack(openN, closedN + 1, n);
stack.pop();
}
}
}