Generate Parentheses
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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
解析
生成给定数字的匹配括号的所有情况。
解法1:递归
定义两个数left和right分别表示左括号和右括号剩余的个数,如果左括号剩余个数大于右括号剩余个数,则违反规定,break,如果left=right=0,合法匹配,则返回,递归调用left和right(大于0时)。
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
recursive(n,n,res,"");
return res;
}
void recursive(int left,int right,vector<string>& res,string str){
if(left>right)
return;
if(left==0 && right==0){
res.push_back(str);
}
else{
if(left>0)
recursive(left-1,right,res,str+'(');
if(right>0)
recursive(left,right-1,res,str+')');
}
}
};
解法2:迭代(set去重)
在上一次出现的所有括号匹配的情况中找下一个数字的匹配情况,找的方法时是:
遍历现有的括号串,碰到左括号就在后面加一对括号,遍历完后在最前面加一对括号,用set去重。
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
if(n==0) return res;
res.push_back("");
for(int i=0;i<n;i++){
set<string> tmp;
for(int j=0;j<res.size();j++){
for(int k=0;k<res[j].size();k++){
if(res[j][k] == '('){
int index = k+1;
string str = res[j];
str.insert(index, "()");
//cout<<str<<endl;
tmp.insert(str);
}
}
tmp.insert("()"+res[j]);
}
res.clear();
res = vector<string>(tmp.begin(),tmp.end());
}
return res;
}
};
参考
https://www.cnblogs.com/grandyang/p/4444160.html