Solved·17 Sept
Generate Parentheses
DifficultyMedium
Patternsubset
TrackDSA
tl;dr
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
full write-up
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Example 1:
Input: n = 3 Output: ["((()))","(()())","(())()","()(())","()()()"] Example 2:
Input: n = 1 Output: ["()"]
Constraints:
1 <= n <= 8
Solution
var generateParenthesis = function(n) {
let result=[];
let output=[]
function backtrack(leftCount,rightCount){
if(leftCount===n && rightCount===n){
result.push(output.join(''))
}
if(leftCount<n){
output.push('(')
backtrack(leftCount+1,rightCount)
output.pop();
}
if(rightCount<leftCount){
output.push(')')
backtrack(leftCount,rightCount+1)
output.pop();
}
}
backtrack(0,0)
return result;
};