DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Generate Paranthesis - I

/**
 * @param {number} n
 * @return {string[]}
 */
var generateParenthesis = function (n) {
  const open = 0;
  const close = 0;
  const tempArray = [];
  const result = [];

  backTrackParanthesis(open, close, tempArray, result, n);
  console.log(result);
};

const backTrackParanthesis = (open, close, tempArray, result, n) => {
  if (open === n && close == n) {
    tempArray = tempArray?.join("");
    result.push(tempArray);
    return true;
  }

  if (close < open) {
    tempArray.push(")");
    backTrackParanthesis(open, close + 1, tempArray, result, n);
    tempArray.pop();
  }

  if (open < n) {
    tempArray.push("(");
    backTrackParanthesis(open + 1, close, tempArray, result, n);
    tempArray.pop();
  }
};

generateParenthesis(3);

Enter fullscreen mode Exit fullscreen mode

Top comments (0)