题目描述
正整数 n
代表生成括号的对数,请设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1
输出:["()"]
提示:
注意:本题与主站 22 题相同: https://leetcode.cn/problems/generate-parentheses/
解法
方法一
1
2
3
4
5
6
7
8
9
10
11
12
13
14 | class Solution:
def generateParenthesis(self, n: int) -> List[str]:
def dfs(left, right, t):
if left == n and right == n:
ans.append(t)
return
if left < n:
dfs(left + 1, right, t + '(')
if right < left:
dfs(left, right + 1, t + ')')
ans = []
dfs(0, 0, '')
return ans
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 | class Solution {
public List<String> generateParenthesis(int n) {
List<String> ans = new ArrayList<>();
dfs(0, 0, n, "", ans);
return ans;
}
private void dfs(int left, int right, int n, String t, List<String> ans) {
if (left == n && right == n) {
ans.add(t);
return;
}
if (left < n) {
dfs(left + 1, right, n, t + "(", ans);
}
if (right < left) {
dfs(left, right + 1, n, t + ")", ans);
}
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 | class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
dfs(0, 0, n, "", ans);
return ans;
}
void dfs(int left, int right, int n, string t, vector<string>& ans) {
if (left == n && right == n) {
ans.push_back(t);
return;
}
if (left < n) dfs(left + 1, right, n, t + "(", ans);
if (right < left) dfs(left, right + 1, n, t + ")", ans);
}
};
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 | func generateParenthesis(n int) []string {
var ans []string
var dfs func(left, right int, t string)
dfs = func(left, right int, t string) {
if left == n && right == n {
ans = append(ans, t)
return
}
if left < n {
dfs(left+1, right, t+"(")
}
if right < left {
dfs(left, right+1, t+")")
}
}
dfs(0, 0, "")
return ans
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 | function generateParenthesis(n: number): string[] {
let ans = [];
let dfs = function (left, right, t) {
if (left == n && right == n) {
ans.push(t);
return;
}
if (left < n) {
dfs(left + 1, right, t + '(');
}
if (right < left) {
dfs(left, right + 1, t + ')');
}
};
dfs(0, 0, '');
return ans;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 | /**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function (n) {
let ans = [];
let dfs = function (left, right, t) {
if (left == n && right == n) {
ans.push(t);
return;
}
if (left < n) {
dfs(left + 1, right, t + '(');
}
if (right < left) {
dfs(left, right + 1, t + ')');
}
};
dfs(0, 0, '');
return ans;
};
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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)
}
}
}
|