Here is the implementation:
function generateParenthesis(n):
result = []
backtrack("", 0, 0)
return result
function backtrack(current, open, close):
if current.length == 2 * n:
result.append(current)
return
if open < n:
backtrack(current + "(", open + 1, close)
if close < open:
backtrack(current + ")", open, close + 1)
The number of valid strings is . Each string has length .