-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path00022-generate_parentheses.java
More file actions
39 lines (30 loc) · 974 Bytes
/
00022-generate_parentheses.java
File metadata and controls
39 lines (30 loc) · 974 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
39
// 22: Generate Parentheses
// https://leetcode.com/problems/generate-parentheses/
import java.util.ArrayList;
import java.util.List;
class Solution {
// SOLUTION
static List<String> result = new ArrayList<>();
public String[] generateParentheses(int n) {
generate(n, 0, 0, "");
return result.toArray(new String[0]);
}
private static void generate(int n, int open, int close, String s) {
if (open==n && close==n) {
result.add(s);
return;
}
if (open < n)
generate(n, open+1, close, s+'(');
if (open > close)
generate(n, open, close+1, s+')');
}
public static void main(String[] args) {
Solution o = new Solution();
// INPUT
int n = 3;
// OUTPUT
var result = o.generateParentheses(n);
System.out.print("["); for (var v : result) System.out.print("\""+v+"\" "); System.out.println("\b]");
}
}