-
Notifications
You must be signed in to change notification settings - Fork 20
/
GenerateParentheses.kt
55 lines (48 loc) · 1.21 KB
/
GenerateParentheses.kt
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
51
52
53
54
55
/**
* Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
*
* For example, given n = 3, a solution set is:
*
* [
* "((()))",
* "(()())",
* "(())()",
* "()(())",
* "()()()"
* ]
*
* Accepted.
*/
class GenerateParentheses {
fun generateParenthesis(n: Int): List<String> {
val set = mutableSetOf<String>()
val list = mutableListOf<String>()
if (n <= 0) {
return list
}
if (n == 1) {
return list.apply {
add("()")
}
}
generateParenthesis(n - 1).forEach { s ->
val sb = StringBuilder()
val chars = s.toCharArray()
for (j in chars.indices) {
sb.append(chars[j])
if (chars[j] == '(') {
val builder = StringBuilder(sb)
builder.append("()")
for (k in j + 1 until chars.size) {
builder.append(chars[k])
}
set.add(builder.toString())
}
}
set.add(s + "()")
}
return list.apply {
addAll(set)
}
}
}