-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGenerateParentheses.java
More file actions
40 lines (32 loc) · 1.17 KB
/
GenerateParentheses.java
File metadata and controls
40 lines (32 loc) · 1.17 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
39
40
// Given n pairs of parentheses, write a function
// to generate all combinations of well-formed parentheses.
// See: https://leetcode.com/problems/generate-parentheses/
package leetcode.backtracking;
import java.util.LinkedList;
import java.util.List;
public class GenerateParentheses {
public List<String> generateParenthesis(int n) {
List<String> result = new LinkedList<String>();
gen(n, result, new StringBuilder(), 0, 0);
return result;
}
public void gen(int n, List<String> result, StringBuilder curr, int open, int close) {
if (curr.length() == n << 1) {
result.add(curr.toString());
}
if (open < n) {
curr.append('(');
gen(n, result, curr, open + 1, close);
curr.setLength(curr.length() - 1);
}
if (close < n && open > close) {
curr.append(')');
gen(n, result, curr, open, close + 1);
curr.setLength(curr.length() - 1);
}
}
public static void main(String[] args) {
GenerateParentheses sln = new GenerateParentheses();
System.out.println(sln.generateParenthesis(3));
}
}