数字 n
代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
示例 1:
1 2
| 输入:n = 3 输出:["((()))","(()())","(())()","()(())","()()()"]
|
示例 2:
提示:
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); } } }
|