括号生成

22. 括号生成

数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。

示例 1:

1
2
输入:n = 3
输出:["((()))","(()())","(())()","()(())","()()()"]

示例 2:

1
2
输入:n = 1
输出:["()"]

提示:

  • 1 <= n <= 8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
List<String> ans = new ArrayList<>();
char[] path;
public List<String> generateParenthesis(int n) {
path = new char[n*2];
dfs(0, 0, n);
return ans;
}

public void dfs(int i, int leftNum, int n){
if(i == n * 2){
ans.add(new String(path));
}
if(leftNum < n){ //可以放入左括号
path[i] = '(';
dfs(i+1, leftNum+1, n);
}
if(i - leftNum < leftNum){ //右括号的数量小于左括号才能放入右括号
path[i] = ')';
dfs(i+1, leftNum, n);
}
}

}

括号生成
http://example.com/2023/09/15/算法/回溯/18. 括号生成/
作者
PALE13
发布于
2023年9月15日
许可协议