[LeetCode] Generate Parentheses 生成括号

给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。

例如,给出 n = 3,生成结果为:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

思路:

/**
 * @param {number} n
 * @return {string[]}
 */
const generateParenthesis = (n) => {
  let res = [];
  Helper(n, n, '', res);
  return res;
};

const Helper = (left, right, str, res)=> {
  if (left > right) return;
  if ((left == 0) & (right == 0)) {
    res.push(str);
  } else {
    if (left > 0) Helper(left - 1, right, str + '(', res);
    if (right > 0) Helper(left, right - 1, str + ')', res);
  }
}

你可能感兴趣的:(Leetcode)