The Generate Parentheses problem involves generating all combinations of well-formed parentheses for a given number n
.
class Solution {
public List<String> generateParenthesis(int n) {
List<String> result = new ArrayList<>();
backtrack(result, new StringBuilder(), 0, 0, n);
return result;
}
private void backtrack(List<String> result, StringBuilder current, int open, int close, int max) {
if (current.length() == max * 2) {
result.add(current.toString());
return;
}
if (open < max) {
current.append("(");
backtrack(result, current, open + 1, close, max);
current.deleteCharAt(current.length() - 1); // Backtrack
}
if (close < open) {
current.append(")");
backtrack(result, current, open, close + 1, max);
current.deleteCharAt(current.length() - 1); // Backtrack
}
}
}
O(4^n / โn)
, where n
is the number of pairs of parentheses. This is the Catalan number complexity.O(n)
, for the recursion stack.Input: n = 3
Output: ["((()))", "(()())", "(())()", "()(())", "()()()"]
Explanation:
- For n = 3, generate all valid combinations of 3 pairs of parentheses.
open
and close
) to track the number of open and close parentheses used so far.open < max
.close < open
.