1. Problem Statement (Simple Explanation):
You are given an integer n, the number of pairs of parentheses.
You must generate all possible combinations of well-formed (valid) parentheses using exactly n pairs.
A string of parentheses is well-formed if:
Every opening '(' has a corresponding closing ')'.
At any point while reading from left to right, the number of ')' never exceeds '('.
2. Examples:
Example 1:
Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]
These are all valid combinations using exactly 3 pairs.
Example 2:
Input: n = 1
Output: ["()"]
Constraints:
1 <= n <= 8
3. Approach – Backtracking (DFS with Constraints):
This is a classic backtracking problem.
Intuition:
We want to build strings of length 2 * n using '(' and ')', but only keep the valid ones.
Instead of generating all 22n possibilities and filtering, we build only valid strings by enforcing rules during construction.
We keep track of:
open = number of '(' used so far
close = number of ')' used so far
Rules to keep the string valid at all times:
We can add '(' if open < n.
We can add ')' if close < open (we can’t close more than we’ve opened).
When the string length reaches 2 * n, we have a complete valid combination.
Algorithm (Step-by-Step):
Initialize an empty result list.
Define a recursive function backtrack(path, open, close):
path: current string being built.
open: number of '(' used.
close: number of ')' used.
Base case:
if len(path) == 2 * n:
Add path to result; return.
Recursive cases:
if open < n: we can add '(':
backtrack(path + "(", open + 1, close)
if close < open: we can add ')':
backtrack(path + ")", open, close + 1)
Start recursion with: backtrack("", 0, 0).
Return the result list.
Pseudo-code:
Asymptotically,
Time: O(Cn) (we generate each valid string once).
Space:
Recursion depth: O(n).
Output size: O(n*Cn) characters total.
For n <= 8, this is very manageable.
4. Java code:
6. C++ code:
7. Python code:
8. JavaScript code:






Comments
Post a Comment