Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
Input: n = 1
Output: ["()"]
A valid parentheses string has these properties:
We can build valid strings character by character using backtracking:
This is a Backtracking problem (often visualized with Stack) with:
Use Backtracking with these rules:
openCount < n
openCount + 1closeCount < openCount
closeCount + 1Why This Works:
1class Solution {
2 public List<String> generateParenthesis(int n) {
3 List<String> result = new ArrayList<>();
4 backtrack(result, "", 0, 0, n);
5 return result;
6 }
7
8 private void backtrack(List<String> result, String current,
9 int openCount, int closeCount, int n) {
10 // Base case: we have a complete valid string
11 if (current.length() == 2 * n) {
12 result.add(current);
13 return;
14 }
15
16 // Add opening bracket if we haven't used all n
17 if (openCount < n) {
18 backtrack(result, current + "(", openCount + 1, closeCount, n);
19 }
20
21 // Add closing bracket if it keeps string valid
22 if (closeCount < openCount) {
23 backtrack(result, current + ")", openCount, closeCount + 1, n);
24 }
25 }
26}
27