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(n), excluding the output

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
    vector<string> generateParenthesis(int n) {
        parentheses.clear();
        string parenthesis;
        generate_parentheses(parenthesis, n, n);

        return move(parentheses);
    }

private:
    vector<string> parentheses;
    void generate_parentheses(string &parenthesis, int left_count, int right_count) {
        if (left_count == 0 && right_count == 0) {
            parentheses.push_back(parenthesis);
            return;
        }

        if (left_count > 0) {
            parenthesis.push_back('(');
            generate_parentheses(parenthesis, left_count - 1, right_count);
            parenthesis.pop_back();
        }

        if (right_count > left_count) {
            parenthesis.push_back(')');
            generate_parentheses(parenthesis, left_count, right_count - 1);
            parenthesis.pop_back();
        }
    }
};
comments powered by Disqus