Generate Parentheses Problem


Description

LeetCode Problem 22.

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

Example 1:

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

Example 2:

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

Constraints:

  • 1 <= n <= 8


Sample C++ Code

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
32
33
34
class Solution {
public:
    string paren = "()";
    vector<string> ans;
    int N;
    
    
    void dfs(string& s, int left, int right) {
        if (s.size() == N*2) {
            ans.push_back(s);
            return;
        }
        
            if (left < N) {
                s += '(';
                dfs(s, left+1, right);
                s.pop_back();
            }
            if (right < left) {
                s += ')';
                dfs(s, left, right+1);
                s.pop_back();
            }

    }
    
    vector<string> generateParenthesis(int n) {
        N = n;
        string s;
        dfs(s, 0, 0);
        
        return ans;
    }
};




Related Posts

Valid Number Problem

LeetCode 65. Given a string s, return true if s...

Text Justification Problem

LeetCode 68. Given an array of strings words and a...

Valid Number Problem

LeetCode 67. A robot is located at the top-left corner...

Length Of Last Word Problem

LeetCode 58. Given a string s consisting of some words...

Zigzag Conversion Problem

LeetCode 6. Write the code that will take a string...

Wildcard Matching Problem

LeetCode 44. Write the code that will take a string...