-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenerateParentheses.java
More file actions
50 lines (43 loc) · 1.42 KB
/
GenerateParentheses.java
File metadata and controls
50 lines (43 loc) · 1.42 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
41
42
43
44
45
46
47
48
49
50
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static java.util.stream.Collectors.toList;
/*
* https://leetcode.com/problems/generate-parentheses/
*/
public class GenerateParentheses {
public List<String> generateParenthesis(int n) {
if (n == 0) {
return Collections.emptyList();
}
return generateParenthesis(n, 0, 0);
}
private List<String> generateParenthesis(int n, int startCount, int endCount) {
if (startCount == endCount && endCount == n) {
return Collections.singletonList("");
}
List<String> list = new ArrayList<>();
if (endCount < startCount) {
list.addAll(generateParenthesis(n, startCount, endCount + 1).stream().map(s -> ")" + s).collect(toList()));
}
if (startCount < n) {
list.addAll(generateParenthesis(n, startCount + 1, endCount).stream().map(s -> "(" + s).collect(toList()));
}
return removeDuplicates(list);
}
private List<String> removeDuplicates(List<String> list) {
return list.stream().distinct().collect(toList());
}
public static void main(String[] args) {
System.out.println(new GenerateParentheses().generateParenthesis(3));
// [
// "((()))",
// "(()())",
// "(())()",
// "()(())",
// "()()()"
// ]
}
}
//[((())()), (())(())]
//[((())())]