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:
"((()))", "(()())", "(())()", "()(())", "()()()"
解题思路:递归的思想。同时要保证‘(’和‘)’配对。
Code:
class Solution {
public:
void DFS(int n,int lpos,int npos,string curStr,vector<string>& ret)
{
if(lpos<npos)
return ;
if(lpos+npos==2*n)
{
if(lpos==npos)
{
ret.push_back(curStr);
}
return ;
}
DFS(n,lpos+1,npos,curStr+'(',ret);
DFS(n,lpos,npos+1,curStr+')',ret);
}
vector<string> generateParenthesis(int n)
{
vector<string> ret;
DFS(n,0,0,"",ret);
return ret;
}
};