forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0022-generate-parentheses.kt
More file actions
31 lines (29 loc) · 897 Bytes
/
0022-generate-parentheses.kt
File metadata and controls
31 lines (29 loc) · 897 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
class Solution {
private val resultList = mutableListOf<String>()
fun generateParenthesis(n: Int): List<String> {
generateParenthesis(n * 2, "")
return resultList
}
private fun generateParenthesis(target: Int, current: String) {
if (current.length == target) {
var open = 0
var close = 0
for (i in 0 until current.length) {
if (current[i] == '(') {
++open
} else {
++close
}
if (close > open) {
break
}
}
if (close == open) {
resultList.add(current)
}
} else {
generateParenthesis(target, "${current}(")
generateParenthesis(target, "${current})")
}
}
}