Leetcode 22. Generate Parentheses

110 阅读1分钟

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

递归可以画图画出函数执行栈
1 利用递归,首先添加 "(", 然后再添加“)”,当字符串的长度等于2*n的时候,停止
比如当n = 3的时候,递归执行顺序如下
(
((
(((
((()
((())
((()))
(()
(()(
(()()
(()())
(())
(())(
(())()
()
()(
()((
()(()
()(())
()()
()()(
()()()

/**
 * @param {number} n
 * @return {string[]}
 */
// res 是最后结果,str是每次拿到字符串,open 是加入了多少个“(”,close 是加入了多少个“)”,max 是一共有多少对“()”

const backtrack = (res, str, open, close, max) => {
  console.log(str);
  if (str.length === max * 2) {
    res.push(str);
    return;
  }

  if (open < max) {
    backtrack(res, str + "(", open + 1, close, max);
  }

  if (close < open) {
    backtrack(res, str + ")", open, close + 1, max);
  }
};
export default (n) => {
  let res = [];
  backtrack(res, "", 0, 0, n);
  return res;
};