0

I am doing a leetcode algorithm, 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:

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

I totally have no idea about that.

I do know the number of combination equals to catalan number

but I don't know how to list all the combinations

anyone could give me some hints ? even no code will be good for me

allencharp
  • 1,101
  • 3
  • 14
  • 31

1 Answers1

2

The idea is to start with ( and the variable left and right to record the number of ( and ) respectively.

Here was my solution:

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;
    }
}
Kaidul
  • 15,409
  • 15
  • 81
  • 150
  • Thanks, your info about what left and right stores was crucial to helping me understand this recursive solution – nickang Jan 01 '18 at 09:09