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:
"((()))", "(()())", "(())()", "()(())", "()()()"
Subscribe to see which companies asked this question
#include <iostream>
#include <cstdio>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
void parenthesis(int num, int cnt, string ans, int n, vector<string>& ans) {
if(num < 0) return ;
if(cnt > n*2) {
if(num == 0) {
ans.push_back(ans);
return;
}
else return;
}
parenthesis(num+1, cnt+1, ans+"(", n, ans);
parenthesis(num-1, cnt+1, ans+")", n, ans);
}
vector<string> generateParenthesis(int n) {
vector<string> ans;
parenthesis(0,0,"", n, ans);
return ans;
}
};
int main() {
return 0;
}