数字?n
?代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且?有效的?括号组合。
示例 1:
输入:n = 3 输出:["((()))","(()())","(())()","()(())","()()()"]
示例 2:
输入:n = 1 输出:["()"]
提示:
1 <= n <= 8
递归(Recursion)
class Solution {
private List<String> res;
public List<String> generateParenthesis(int n) {
// Recursion
// Time: O(2^n)
// Space: O(n)
res = new ArrayList<>();
_generate(0, 0, n, "");
return res;
}
private void _generate(int left, int right, int n, String s) {
// terminator
if (left == n && right == n) {
res.add(s);
return;
}
// process current logic: left, right
// drill down
if (left < n) _generate(left + 1, right, n, s + "(");
if (right < left) _generate(left, right + 1, n, s + ")");
// reverse states
}
}