Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit f1ddfb4

Browse files
Create 22-Generate-Paranthesis.java
1 parent 51bcb14 commit f1ddfb4

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

java/22-Generate-Paranthesis.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class GenerateParentheses {
2+
public List<String> generateParentheses(int n) {
3+
List<String> result = new ArrayList<>();
4+
Stack<String> stack = new Stack<>();
5+
6+
backtrack(0, 0, n, result, stack);
7+
return result;
8+
}
9+
10+
public void backtrack(int open, int closed, int n, List<String> result, Stack<String> stack) {
11+
if (open == n && closed == n) {
12+
result.add(stack.stream().collect(Collectors.joining("")));
13+
}
14+
15+
if (open < n) {
16+
stack.push("(");
17+
backtrack(open + 1, closed, n, result, stack);
18+
stack.pop();
19+
}
20+
21+
if (closed < open) {
22+
stack.push(")");
23+
backtrack(open, closed + 1, n, result, stack);
24+
stack.pop();
25+
}
26+
}
27+
}

0 commit comments

Comments
 (0)