您的位置:首页 > 其它

22. Generate Parentheses

2016-04-21 10:44 295 查看
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,表示需要产生n个左括号,右括号为0。如果当前选择左括号,则left计数减一,并且右括号数量加1,表示当前需要产生right个右括号来匹配左括号。当左右计数器都为0,则表明已经把左右括号全部产生完,此分支结束。


class Solution {
public:
void DFS(vector<string> &result, string str, int left, int right)
{
if(left==0 && right ==0){
result.push_back(str);
return;
}
if(left > 0)
{
DFS(result, str+"(", left-1, right +1 );
}
if(right > 0)
{
DFS(result, str+")", left, right-1);
}
}
vector<string> generateParenthesis(int n) {
vector<string> result;
if(n<=0) return result;
string str;
DFS(result, str, n,0);
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: