leetcode22 Generate Parentheses
# 22. 括号生成 (opens new window)
English Version (opens new window)
# 题目描述
数字 n
代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3 输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1 输出:["()"]
提示:
1 <= n <= 8
# 解法
dfs
# Python3
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
def dfs(ans, l, r, n):
if len(ans) == (n << 1):
self.res.append(ans)
return
if l < n:
dfs(ans + '(', l + 1, r, n)
if r < l:
dfs(ans + ')', l, r + 1, n)
self.res = []
dfs('', 0, 0, n)
return self.res
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# Java
class Solution {
public List<String> generateParenthesis(int n) {
List<String> res = new ArrayList<>();
dfs(res, "", 0, 0, n);
return res;
}
private void dfs(List<String> res, String ans, int l, int r, int n) {
if (ans.length() == (n << 1)) {
res.add(ans);
return;
}
if (l < n) {
dfs(res, ans + "(", l + 1, r, n);
}
if (r < l) {
dfs(res, ans + ")", l, r + 1, n);
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# TypeScript
function generateParenthesis(n: number): string[] {
let ans = [];
dfs(n, 0, 0, '', ans);
return ans;
};
function dfs(n: number, left: number, right: number, str: string, ans: string[]) {
if (str.length == 2 * n) {
ans.push(str);
return;
}
if (left < n) {
dfs(n, left + 1, right, str + '(', ans);
}
if (right < left) {
dfs(n, left, right + 1, str + ')', ans);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# C++
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
dfs(res, "", 0, 0, n);
return res;
}
private:
void dfs(vector<string>& res, string ans, int l, int r, int n) {
if (ans.size() == (n << 1)) {
res.push_back(ans);
return;
}
if (l < n) dfs(res, ans + "(", l + 1, r, n);
if (r < l) dfs(res, ans + ")", l, r + 1, n);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Go
func generateParenthesis(n int) []string {
res := new([]string)
dfs(res, "", 0, 0, n)
return *res
}
func dfs(res *[]string, ans string, l, r, n int) {
if len(ans) == (n << 1) {
*res = append(*res, ans)
return
}
if l < n {
dfs(res, ans+"(", l+1, r, n)
}
if r < l {
dfs(res, ans+")", l, r+1, n)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# ...
1
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38