[LeetCode] 22. Generate Parentheses

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:
[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

Thought process:
The idea is to recursively add and remove parentheses in a string. When the string's length reaches 2 * n, we have our base case and we can add the string to result list.
To make sure the parentheses are well-formed, we can use two counters: open and close, which tracks open parenthesis and close parenthesis respectively. When open < n, we can add more open parentheses; when close < open, we can add more close parentheses.

Solution:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> parentheses;
        generateParentheses(n, "", parentheses, 0, 0);
        return parentheses;
    }
    
    void generateParentheses(int n, string s, vector<string>& parentheses, int open, int close) {
        if (s.length() == 2 * n) {
            parentheses.push_back(s);
            return;
        }
        
        if (open < n) {
            generateParentheses(n, s + "(", parentheses, open + 1, close);
        }
        
        if (close < open) {
            generateParentheses(n, s + ")", parentheses, open, close + 1);
        }
    }
};

It's okay to overload a function with a different return type.

Time complexity:

Same as combinations: O(n!).

Comments

Popular posts from this blog

[LeetCode] 631. Design Excel Sum Formula

[LeetCode] 714. Best Time to Buy and Sell Stock with Transaction Fee

[LeetCode] 269. Alien Dictionary