Skip to content

Latest commit

 

History

History
30 lines (25 loc) · 790 Bytes

括号生成.md

File metadata and controls

30 lines (25 loc) · 790 Bytes

https://leetcode-cn.com/problems/generate-parentheses/

思路

代码

/**
 * @param {number} n
 * @return {string[]}
 */
var generateParenthesis = function(n) {
  const res = []
  const dfs = (index, lRemain, rRemain, str) => {
    if (str.length == 2 * n) res.push(str)
    for(let i = index; i < n * 2; i++) {
      if (lRemain > 0) {         // 只要左括号有剩,就可以选它,然后继续做选择(递归)
        dfs(i+1, lRemain - 1, rRemain, str + "(");
      }
      if (lRemain < rRemain) {   // 右括号比左括号剩的多,才能选右括号
        dfs(i+1, lRemain, rRemain - 1, str + ")"); // 然后继续做选择(递归)
      }
    }
  }
  dfs(0, n, n, '')
  return res
};