您的位置:首页 > 其它

Generate Parentheses (括号匹配)【leetcode】

2013-09-19 00:41 393 查看
题目: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:

"((()))",
"(()())", "(())()", "()(())", "()()()"

列举所有满足条件的字符串,递归求解,只需要满足做括号不超过n个,右括号个数小于等于左括号。

char str[10000];
vector<string>ll;
class Solution {
public:
vector<string> generateParenthesis(int n) {
ll.clear();
hehe(0,n*2,0,0);
return ll;
}

void hehe(int i,int n,int leftnum,int rightnum)
{
if(i==n)
{
str
='\0';
string temp;
temp=str;
ll.push_back(temp);
return;
}
if(leftnum+1<=n/2)
{
str[i]='(';
hehe(i+1,n,leftnum+1,rightnum);
}
if(leftnum>rightnum)
{
str[i]=')';
hehe(i+1,n,leftnum,rightnum+1);
}

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息