Problem Statement:
Given an integer n
, generate all possible strings that contain n
pairs of balanced parentheses. A balanced parentheses string has properly nested pairs of opening and closing parentheses.
Approach:
The core idea behind generating all possible balanced parentheses strings of n
pairs is to use a recursive backtracking approach. The main challenge is to ensure that, at any point in constructing the string, the parentheses remain balanced. This means that at no point should the number of closing parentheses )
exceed the number of opening parentheses (
, and the total number of (
and )
should both be exactly n
by the end of the construction.
Step-by-Step Explanation:
-
Recursive Function Design:
- We use a recursive function
generateParenthesis
that keeps track of:open
: the number of opening parentheses used so far.close
: the number of closing parentheses used so far.str
: the current string being constructed.result
: a vector that stores all valid balanced parentheses strings.
- We use a recursive function
-
Base Case:
- The recursion stops when both
open
andclose
equaln
, which means we’ve used alln
pairs of parentheses. The constructed stringstr
is then a valid balanced parentheses string and is added to theresult
vector.
- The recursion stops when both
-
Recursive Steps:
- Add an Opening Parenthesis: If the number of opening parentheses used so far (
open
) is less thann
, we can add an opening parenthesis(
to the current string and make a recursive call to build further. - Add a Closing Parenthesis: If the number of closing parentheses used so far (
close
) is less than the number of opening parentheses (open
), we can add a closing parenthesis)
to the current string and make a recursive call.
- Add an Opening Parenthesis: If the number of opening parentheses used so far (
-
Termination:
- The function continues recursively adding opening and closing parentheses while maintaining the validity of the string until all combinations are exhausted.
Time Complexity:
- The time complexity is
O(2^2n)
or exponential, as the number of valid balanced parentheses strings grows exponentially withn
. - However, the backtracking ensures that only valid strings are generated, making it much more efficient than brute-force generation of all possible strings.