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

String Without Aaa Or Bbb Problem

LeetCode 984. Given two integers a and b, return any...

Shifting Letters Problem

LeetCode 848. You are given a string s of lowercase...

Positions Of Large Groups Problem

LeetCode 830. In a string sof lowercase letters, these letters...

Orderly Queue Problem

LeetCode 899. You are given a string s and an...

Number Of Lines To Write String Problem

LeetCode 806. You are given a string s of lowercase...

Masking Personal Information Problem

LeetCode 831. You are given a personal information string s,...