Generate Parentheses
Problem statement
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3Output: ["((()))","(()())","(())()","()(())","()()()"]
Example 2:
Input: n = 1Output: ["()"]
Constraints:
1 <= n <= 8
My solution
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
const results = [];
function parse(left, right, str) {
if (left > right) {
return;
}
if (left === 0 && right === 0) {
results.push(str)
return;
}
if (left > 0) {
parse(left - 1, right, str + "(")
}
if (right > 0) {
parse(left, right - 1, str + ")")
}
}
parse(n, n, "");
return results;
};