您的位置:首页 > 其它

LeetCode——022

2016-04-16 11:26 288 查看


/*

22. Generate Parentheses My Submissions QuestionEditorial Solution

Total Accepted: 85070 Total Submissions: 231341 Difficulty: Medium

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

能够往下走的条件就是左括号数 、右括号数有没达到n值得。在每一步过程中必须保证left>=right,否则返回

*/

class Solution {
public:
vector<string> generateParenthesis(int n) {

//此题用深度遍历即可
vector<string> res;
dfs(n,0,0,"",res);
return res;
}

void dfs(int n,int left,int right,string out,vector<string>&res){

if(left==n&& right==n){
res.push_back(out);
return ;
}
if(right>left || left>n )return ;
dfs(n,left+1,right,out+'(',res);
dfs(n,left,right+1,out+')',res);
}

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