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

Commit 29f5618

Browse files
22. Generate Parentheses
1 parent e00b5e7 commit 29f5618

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/// The time and space complexity of this code is `O(4^n / √n)`
2+
3+
class Solution {
4+
List<String> generateParenthesis(int n) {
5+
List<String> result = [];
6+
7+
_generate(result, "", 0, 0, n);
8+
9+
return result;
10+
}
11+
12+
void _generate(List<String> result, String current, int open, int close, int n) {
13+
if (current.length == n * 2) {
14+
result.add(current);
15+
return;
16+
}
17+
if (open < n) {
18+
_generate(result, "$current(", open + 1, close, n);
19+
}
20+
if (close < open) {
21+
_generate(result, "$current)", open, close + 1, n);
22+
}
23+
}
24+
}
25+
26+
void main(List<String> args) {
27+
print(Solution().generateParenthesis(3));
28+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
22. Generate Parentheses
2+
https://leetcode.com/problems/generate-parentheses/
3+
4+
Given n pairs of parentheses, write a function to generate
5+
all combinations of well-formed parentheses.
6+
7+
8+
Example 1:
9+
10+
Input: n = 3
11+
Output: ["((()))","(()())","(())()","()(())","()()()"]
12+
13+
Example 2:
14+
15+
Input: n = 1
16+
Output: ["()"]
17+
18+
19+
Constraints:
20+
21+
1 <= n <= 8

0 commit comments

Comments
(0)

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