leetcode 22. 括号生成

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/generate-parentheses
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 1 public class _22 {
 2 
 3     // left表示左括号数量,right表示右括号数量
 4     public void solve(int n, int left, int right, List<String> res,char[] s, int i){ // i表示char数组中改动的位置
 5         if (left > n || right > n || right > left) {
 6             return ;
 7         }
 8         if (left == right && left == n){
 9             res.add(String.valueOf(s));
10         }
11         if (i >= 2*n)
12             return;
13 
14         // 选择‘(’
15         s[i] = '(';
16         solve(n, left+1, right, res, s, i+1);
17 
18         // 选择‘)’
19         s[i] = ')';
20         solve(n, left, right+1, res, s, i+1);
21     }
22 
23     public List<String> generateParenthesis(int n) {
24         char[] s = new char[2*n];
25         List<String> list = new ArrayList<>();
26         solve(n, 0, 0, list, s, 0);
27 
28         return list;
29     }
30 
31     public static void main(String[] args) {
32         List<String> list = new _22().generateParenthesis(3);
33         for (String s : list){
34             System.out.println(s);
35         }
36     }
37 }
原文地址:https://www.cnblogs.com/yfs123456/p/11517747.html