问题详情
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对括号的排序方式。
上图为从这里找到的图,由于这个人的算法思路讲的很好,帮助了我理解算法,所以此处贴出他的图,算法也在上面一清二楚。
我在将自己的代码优化、与他的代码结合,进一步帮助我理解了dfs。
具体代码
class Solution {
public:
vector<string> generateParenthesis(int n) {
string now;
helper(n,n,now);
return result;
}
private:
vector<string> result;
void helper(int left,int right,string now)
{
if(left==0&&right==0)
{
result.push_back(now);
return ;
}
if(left!=0)
helper(left-1,right,now+"(");
if(right!=0&&left<right)
helper(left,right-1,now+")");
}
};