Skip to content

Instantly share code, notes, and snippets.

@sAVItar02
Created November 25, 2024 13:33
Show Gist options
  • Save sAVItar02/106b7d105050fbc4ef2401ca70b91ea9 to your computer and use it in GitHub Desktop.
Save sAVItar02/106b7d105050fbc4ef2401ca70b91ea9 to your computer and use it in GitHub Desktop.
Generate Parentheses
/**
* @param {number} n
* @return {string[]}
*/
var generateParenthesis = function(n) {
let res = [];
function rec(open, close, string = "") {
if((open == close) && (open + close == 2*n)) {
res.push(string);
return;
}
if(open < n) {
rec(open+1, close, string + "(");
}
if(close < open) {
rec(open, close+1, string + ")");
}
}
rec(0, 0, "");
return res;
};
// If Open < n ----> add open parentheses
// if close < open and open < n add either open parentheses or closed parentheses
// if close < open and open ! < n add closed parentheses
// if open == close and open == close == n ------> push string into res
// Time: O(2^n)
// Space: O(n)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment