Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit 14d3b70

Browse files
authored
Create 22. Generate Parentheses.md
1 parent 6da5aa2 commit 14d3b70

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

‎22. Generate Parentheses.md‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# 22. Generate Parentheses
2+
3+
### 2022年05月09日
4+
5+
Given `n` pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
6+
7+
8+
9+
Example 1:
10+
```
11+
Input: n = 3
12+
Output: ["((()))","(()())","(())()","()(())","()()()"]
13+
```
14+
15+
Example 2:
16+
```
17+
Input: n = 1
18+
Output: ["()"]
19+
```
20+
21+
22+
23+
# Solution
24+
25+
```swift
26+
class Solution {
27+
28+
private func generateParenthesis(left: Int, right: Int, max: Int, str: String, result: inout [String]) {
29+
if left == max, right == max {
30+
result.append(str)
31+
return
32+
}
33+
if left < max {
34+
generateParenthesis(left: left + 1, right: right, max: max, str: str + "(", result: &result)
35+
}
36+
if left > right {
37+
generateParenthesis(left: left, right: right + 1, max: max, str: str + ")", result: &result)
38+
}
39+
}
40+
41+
func generateParenthesis(_ n: Int) -> [String] {
42+
var temp = [String]()
43+
generateParenthesis(left: 0, right: 0, max: n, str: "", result: &temp)
44+
return temp
45+
}
46+
}
47+
48+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /