您的位置:首页 > 其它

22. Generate Parentheses

2016-03-11 11:12 204 查看
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:

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

解题思路:

DFS

class Solution {

public:

vector<string> generateParenthesis(int n) {

vector<string>res;

if(n==0)return res;

dfs(res,n,0,0,"");

return res;

}

void dfs(vector<string>&res,int n,int l,int r,string s){

if(l==n&&r==n){

res.push_back(s);

return ;

}

if(l==n){

dfs(res,n,l,r+1,s+")");

return ;

}

if(l==r){

dfs(res,n,l+1,r,s+"(");

return ;

}

dfs(res,n,l+1,r,s+"(");

dfs(res,n,l,r+1,s+")");

}

};

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