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) {
        string parenthesis;
        parenthesis.reserve(2 * n);
        vector<string> results;
        generate_parenthesis(parenthesis, n, n, results);

        return results;
    }

private:
    void generate_parenthesis(string &parenthesis, int left, int right, vector<string> &results) {
        if (left == 0 && right == 0) {
            results.push_back(parenthesis);
        } else {
            if (left > 0) {
                parenthesis.push_back('(');
                generate_parenthesis(parenthesis, left - 1, right, results);
                parenthesis.pop_back();
            }

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