22. Generate Parentheses

1. Description

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

2. Example

Example 1

Input: n = 3
Output: ["((()))","(()())","(())()","()(())","()()()"]

Example 2

Input: n = 1
Output: ["()"]

3. Constraints

  • 1 <= n <= 8

4. Solutions

Backtracking

Time complexity: O($\frac {4^n} {\sqrt{n}}$)
Space complexity: O($\frac {4^n} {\sqrt{n}}$)

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> parentheses;
        string parenthesis;
        parenthesis.reserve(2 * n);
        generate_parenthesis(parentheses, parenthesis, n, n);

        return parentheses;
    }

private:
    void generate_parenthesis(
        vector<string> &parentheses,
        string &parenthesis,
        int left,
        int right) {
        if (left == 0 && right == 0) {
            parentheses.push_back(parenthesis);
            return;
        }

        if (left > 0) {
            parenthesis.push_back('(');
            generate_parenthesis(parentheses, parenthesis, left - 1, right);
            parenthesis.pop_back();
        }
        if (right > left) {
            parenthesis.push_back(')');
            generate_parenthesis(parentheses, parenthesis, left, right - 1);
            parenthesis.pop_back();
        }
    }
};
comments powered by Disqus