22. Generate Parentheses
Intitution
To generate all valid combinations of n
pairs of parentheses, we can use backtracking. A valid parentheses combination must always have:
An equal number of opening
'('
and closing')'
parentheses.At no point in the combination can the number of closing brackets exceed the number of opening ones.
We build the string character by character, ensuring that we only add an opening bracket '('
when we still have quota left, and a closing bracket ')'
only if it balances out a previous '('
.
Complexity
Space Complexity
Time Complexity
Code
Last updated