-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerateParanthesis.java
More file actions
38 lines (34 loc) · 983 Bytes
/
GenerateParanthesis.java
File metadata and controls
38 lines (34 loc) · 983 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
package Stack;
import java.util.*;
/*
22. Generate Parentheses
*/
public class GenerateParanthesis {
Stack<String> stack = new Stack<>();
List<String> res = new ArrayList<>();
public List<String> generateParenthesis(int n) {
if (n==0) return res;
backTracking(0,0,n);
return res;
}
public void backTracking(int openCount, int closedCount, int n){
if(openCount==n && closedCount==n){
Iterator<String> val = stack.iterator();
StringBuilder p = new StringBuilder();
while (val.hasNext()) {
p.append(val.next());
}
res.add(p.toString());
}
if(openCount<n){
stack.push("(");
backTracking(openCount+1,closedCount,n);
stack.pop();
}
if(closedCount<openCount){
stack.push(")");
backTracking(openCount,closedCount+1,n);
stack.pop();
}
}
}