22. Generate Parentheses

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

Problem

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:

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

Solution

1. Naive

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        if (n == 0) return vector<string>{""};
        vector<string> paren;
        for (int i = 0; i < n; ++i) {
            for (const auto &p: generateParenthesis(i)) {
                string left = "(" + p + ")";
                for (const auto &right: generateParenthesis(n - 1- i)) {
                    paren.push_back(left + right);
                }
            }
        }
        return paren;
    }
};

2. Optimized using shared variable

  • #recursion

  • #dp

Last updated

Was this helpful?