The number n
represents the number of parentheses to be generated. Please design a function that can generate all possible and valid combinations of parentheses.
Use backtracking. In the code above, startCount
represents the number of left parentheses, endCount
represents the number of right parentheses, str
is the cached string, target
is the target array, and n
is the number of pairs of parentheses. During the recursion, when startCount
is less than n
, add (
to the cached string and increase startCount
by 1, then pass the updated parameters to the next recursion. When endCount
is less than startCount
, add )
to the cached string and increase endCount
by 1, then pass the updated parameters to the next recursion. When the length of the string is equal to n*2
, the recursion ends and the cached string is added to the target array.