-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGenerateParenthesis.java
More file actions
38 lines (29 loc) · 930 Bytes
/
GenerateParenthesis.java
File metadata and controls
38 lines (29 loc) · 930 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 com.company;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
public class GenerateParenthesis {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList();
backtrack(ans, "", 0, 0, n);
return ans;
}
public void backtrack(List<String> ans, String cur,
int open, int close, int max) {
if (cur.length() == max * 2) {
ans.add(cur);
return;
}
if (open < max)
backtrack(ans, cur + "(", open + 1, close, max);
if (close < open)
backtrack(ans, cur + ")", open, close + 1, max);
}
@Test
public void test() {
List<String> generateParenthesis = generateParenthesis(3);
for (String str : generateParenthesis) {
System.out.println(str);
}
}
}