Skip to content

Commit

Permalink
feat: add swift implementation to lcof2 problem: No.085 (#3470)
Browse files Browse the repository at this point in the history
  • Loading branch information
klever34 authored Sep 2, 2024
1 parent adf71ed commit d7c998a
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,31 @@ var generateParenthesis = function (n) {
};
```

#### Swift

```swift
class Solution {
func generateParenthesis(_ n: Int) -> [String] {
var ans = [String]()
dfs(0, 0, n, "", &ans)
return ans
}

private func dfs(_ left: Int, _ right: Int, _ n: Int, _ t: String, _ ans: inout [String]) {
if left == n && right == n {
ans.append(t)
return
}
if left < n {
dfs(left + 1, right, n, t + "(", &ans)
}
if right < left {
dfs(left, right + 1, n, t + ")", &ans)
}
}
}
```

<!-- tabs:end -->

<!-- solution:end -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Solution {
func generateParenthesis(_ n: Int) -> [String] {
var ans = [String]()
dfs(0, 0, n, "", &ans)
return ans
}

private func dfs(_ left: Int, _ right: Int, _ n: Int, _ t: String, _ ans: inout [String]) {
if left == n && right == n {
ans.append(t)
return
}
if left < n {
dfs(left + 1, right, n, t + "(", &ans)
}
if right < left {
dfs(left, right + 1, n, t + ")", &ans)
}
}
}

0 comments on commit d7c998a

Please sign in to comment.