gold-8-9


括号。设计一种算法,打印n对括号的所有合法的(例如,开闭一一对应)组合。

说明:解集不能包含重复的子集。

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

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

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<>();
        doGenerate(result, "", 0, 0, n);
        return result;
    }

    private void doGenerate(List<String> result, String curRes, int left, int right, int n) {
        if (left == n && right == n) {
            result.add(new String(curRes));
            return;
        }

        if (right < left) {
            doGenerate(result, curRes + ')', left, right + 1, n);
        }

        if (left < n) {
            doGenerate(result, curRes + '(', left + 1, right, n);
        }
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !