-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode0022.java
More file actions
33 lines (28 loc) · 902 Bytes
/
Copy pathLeetCode0022.java
File metadata and controls
33 lines (28 loc) · 902 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
/* Generate Parentheses
* Example 1:
* Input: n = 3
* Output: ["((()))","(()())","(())()","()(())","()()()"]
* */
import java.util.ArrayList;
import java.util.List;
public class LeetCode0022 {
public static void main(String args[]) {
int n = 3;
System.out.println(generateParenthesis(n));
}
public static List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<String>();
backtrack(ans, "", 0, 0, n);
return ans;
}
public static 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);
}
}