Skip to content

Latest commit

 

History

History
45 lines (39 loc) · 1.13 KB

generate-parentheses.md

File metadata and controls

45 lines (39 loc) · 1.13 KB

Generate Parentheses

Problem Link

Given an integer N representing the number of pairs of parentheses, the task is to generate all combinations of well-formed(balanced) parentheses.

Sample Input

3

Sample Output

((()))
(()())
(())()
()(())
()()()

Solution

class Solution {
    public:
    void pattern(int n, int open, int close, string s, vector<string> &ans) {
        if(open == n && close == n) {
            return ans.push_back(s);
        }
        if(open < n) {
            pattern(n, open + 1, close, s + '(', ans);
        }
        if(open > close) {
            pattern(n, open, close + 1, s + ')', ans);
        }
    }

    vector<string> AllParenthesis(int n) {
        vector<string> ans;
        pattern(n, 0, 0, "", ans);
        return ans;
    }
};

Accepted

image