Problem Description
Given n pairs of parentheses, the task is to generate all combinations of well-formed (i.e. valid) parentheses.
Key Insights
- Use a backtracking approach to build the valid combinations step by step.
- At any recursion step, you can add an opening parenthesis if you still have one available.
- You can add a closing parenthesis only if it would not result in an invalid sequence (i.e., the number of closing parentheses is less than the number of opening ones).
- The solution leverages recursion to explore all potential valid sequences while pruning invalid paths early.
Space and Time Complexity
Time Complexity: O(4^n / (n^(3/2))) Space Complexity: O(n) for the recursion stack, plus space for storing all valid combinations.
Solution
The solution uses a recursive backtracking technique to generate the combinations. The algorithm maintains counters for the number of '(' and ')' added to the current string. It recursively adds a '(' if the count is less than n and adds a ')' if doing so does not make the string invalid (i.e., if the count of ')' is less than the count of '('). When a valid combination reaches a length of 2*n, it is added to the result list.