leetcode生成括号算法

时间:2016-10-19 07:01:01

标签: java python algorithm

我正在做一个leetcode算法,link

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:

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

我完全不知道。

我知道组合的数量等于加泰罗尼亚数

但我不知道如何列出所有组合

谁能给我一些提示?即使没有代码对我有好处

1 个答案:

答案 0 :(得分:1)

我们的想法是从(开始,左右变量分别记录()的数量。

这是我的解决方案:

public class Solution {
    private void helper(List<String> res, String present, int left, int right, int n) {
        // When you've finished adding all parenthesis
        if (left == n and right == n) {
            res.push_back(str);
            return;
        }
        // You have left parenthesis available to add
        if (left < n) {
            helper(res, present + "(", left + 1, right, n);
        }
        // You can add right parenthesis only when you have more left parenthesis already added otherwise it won't be balanced
        if (left > right) {
            helper(res, present + ")", left, right + 1, n);
        }
    }

    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<String>();
        if (n == 0) {
            return res;
        }
        helper(res, "", 0, 0, n);
        return res;
    }
}