Skip to content

Commit d7c998a

Browse files
authored
feat: add swift implementation to lcof2 problem: No.085 (#3470)
1 parent adf71ed commit d7c998a

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

lcof2/剑指 Offer II 085. 生成匹配的括号/README.md

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,31 @@ var generateParenthesis = function (n) {
188188
};
189189
```
190190

191+
#### Swift
192+
193+
```swift
194+
class Solution {
195+
func generateParenthesis(_ n: Int) -> [String] {
196+
var ans = [String]()
197+
dfs(0, 0, n, "", &ans)
198+
return ans
199+
}
200+
201+
private func dfs(_ left: Int, _ right: Int, _ n: Int, _ t: String, _ ans: inout [String]) {
202+
if left == n && right == n {
203+
ans.append(t)
204+
return
205+
}
206+
if left < n {
207+
dfs(left + 1, right, n, t + "(", &ans)
208+
}
209+
if right < left {
210+
dfs(left, right + 1, n, t + ")", &ans)
211+
}
212+
}
213+
}
214+
```
215+
191216
<!-- tabs:end -->
192217

193218
<!-- solution:end -->
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
class Solution {
2+
func generateParenthesis(_ n: Int) -> [String] {
3+
var ans = [String]()
4+
dfs(0, 0, n, "", &ans)
5+
return ans
6+
}
7+
8+
private func dfs(_ left: Int, _ right: Int, _ n: Int, _ t: String, _ ans: inout [String]) {
9+
if left == n && right == n {
10+
ans.append(t)
11+
return
12+
}
13+
if left < n {
14+
dfs(left + 1, right, n, t + "(", &ans)
15+
}
16+
if right < left {
17+
dfs(left, right + 1, n, t + ")", &ans)
18+
}
19+
}
20+
}

0 commit comments

Comments
 (0)