题目链接:https://leetcode.com/problems/generate-parentheses/
题面:
22. Generate Parentheses
Medium
2848177FavoriteShare
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:
[ "((()))", "(()())", "(())()", "()(())", "()()()" ]
题意:
产生长度为2*n的合法括号对。
解题:
掌握左括号数不超过右括号数的性质去构造就可以了。
代码:
class Solution {
public:
struct sta{
string s;
int a,b;
};
queue <sta> qe;
vector<string> generateParenthesis(int n) {
vector <string> res;
sta cur,tmp;
int a,b;
tmp.a=tmp.b=0;
qe.push(tmp);
while(!qe.empty()){
cur=qe.front();
qe.pop();
a=cur.a;
b=cur.b;
if(a<n){
tmp.a=a+1;
tmp.b=b;
tmp.s=cur.s+"(";
qe.push(tmp);
}
if(b==n)
res.push_back(cur.s);
else if(b<a){
tmp.a=a;
tmp.b=b+1;
tmp.s=cur.s+")";
qe.push(tmp);
}
}
return res;
}
};