您的位置:首页 > 其它

LeetCode 22 Generate Parentheses

2017-06-05 11:44 417 查看

题目

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:

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]


解法

使用递归的方法得到所有括号的正确组合形式。用left和right来表示左右括号的剩余数量,右括号的剩余数量大于左括号时才能增加右括号。

class Solution {
public:
void DFS(vector<string> &res, int left, int right, string s) {
if(left == 0 && right == 0) res.push_back(s);
if(left > 0) DFS(res, left-1, right, s+"(");
if(right > 0 && left < right) DFS(res, left, right-1, s+")");
}

vector<string> generateParenthesis(int n) {
vector<string> res;
DFS(res,n,n,"");
return res;

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