forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0022-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
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) {
Iterator vale = stack.iterator();
String temp = "";
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();
}
}
}