-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerateParentheses.java
More file actions
38 lines (32 loc) · 1.06 KB
/
GenerateParentheses.java
File metadata and controls
38 lines (32 loc) · 1.06 KB
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
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.stream.Collectors;
public class GenerateParentheses {
Stack<String> stack = new Stack<>();
List<String> result = new ArrayList<>();
void browseParentheses(int opening, int closing, int n) {
if ((opening == n) && (closing == n)) {
result.add(String.join("", stack));
} else {
if (opening < n) {
stack.push("(");
browseParentheses(opening + 1, closing, n);
stack.pop();
}
if (closing < opening) {
stack.push(")");
browseParentheses(opening, closing + 1, n);
stack.pop();
}
}
}
public List<String> generateParenthesis(int n) {
browseParentheses(0, 0, n);
return result;
}
public static void main(String[] args) {
GenerateParentheses generateParentheses = new GenerateParentheses();
System.out.println(generateParentheses.generateParenthesis(3));
}
}