-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0022.Generate Parentheses.swift
60 lines (50 loc) · 1.46 KB
/
0022.Generate Parentheses.swift
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
56
57
58
59
60
class Solution {
private var answer = [String]()
func generateParenthesis(_ n: Int) -> [String] {
recurse_v2("", 0, 0, n)
return answer
// return recurse(n)
}
private func recurse(_ n: Int) -> [String] {
var res = [String]()
if n == 0 {
res.append("")
} else {
for i in 0..<n {
for left in recurse(i) {
for right in recurse(n-1-i) {
res.append("(\(left))\(right)")
}
}
}
}
return res
}
private func recurse_v2(_ current: String, _ open: Int, _ closed: Int, _ n: Int) {
if current.count == n*2 {
answer.append(current)
return
}
if open < n {
recurse_v2(current + "(", open+1, closed, n)
}
if closed < open {
recurse_v2(current + ")", open, closed+1, n)
}
}
private func generateParenthesis_v1(_ n: Int) -> [String] {
var dp = Array(repeating: Set<String>(), count: n)
dp[0] = ["()"]
if n == 1 {
return ["()"]
}
for i in 1..<n {
for el in dp[i-1] {
dp[i].insert("(\(el))")
dp[i].insert("\(el)()")
dp[i].insert("()\(el)")
}
}
return Array(dp[n-1])
}
}