22_Generate Parentheses
[Medium][String, Backtracking]
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example:
Solution:
Idea:
Generate parentheses one by one. At each position, there are 3 possibilities:
Add "(": if there are "(" remains to be added.
Add ")": If the number of ")" is less than the number of "(" in the prefix.
Write recursion at each position for the two possibilities.
Space Complexity: only need space for the output
Last updated