Skip to content

括号组合 #10

Open
Open

Description

@louzhedong

题目

出处:LeetCode 算法第22题

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

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

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

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

思路

按正常的思路去思考会感觉无从下手,需要有一个转换的过程,有效组合中左括号和右括号的总数是相等的,而且在构建有效序列的时候左括号的数量始终都是不小于右括号的数量的,如果出现了左括号的数量小于右括号的数量,那本次解法就是错误的。思路是递归地构建序列,遍历所有组合,得到有效的组合。

解答

var generateParenthesis = function (n) {
  var result = [];
  DFS(n, n, "", result);
  return result;
};

function DFS(left, right, temp, result) {
  if (left > right) {
    return;
  }
  if (left === 0 && right === 0) {
    result.push(temp);
  } else {
    if (left > 0) {
      DFS(left - 1, right, temp + '(', result);
    }
    if (right > 0) {
      DFS(left, right - 1, temp + ')', result);
    }
  }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions