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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
Subscribe to see which companies asked this question
题目不难理解,做的搜索,不过第一次写dfs,
class Solution {
private:
vector<string> vc;
public:
vector<string> generateParenthesis(int n) {
vc.clear();
dfs("(",1,0,n);
return vc;
}
void dfs(string ans,int lnum,int rnum,int n){
if(lnum>n || rnum>n) return;
if((lnum==n)&&(rnum==n)){
vc.push_back(ans);
return ;
}
else{
dfs(ans+'(',lnum+1,rnum,n);
if(lnum>rnum){
dfs(ans+')',lnum,rnum+1,n);
}
}
}
};
大家都在减,,,23333