您的位置:首页 > 其它

[leetcode] 22. Generate Parentheses

2016-01-04 17:17 405 查看
Givenn pairs of parentheses, write a function to
generate all combinations of well-formed parentheses.

For example, givenn = 3, a solution set is:

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

这道题是生成匹配的括号对,题目难度为Medium。

比较直观的想法是在2*n个位置上逐个放置‘(’或‘)’,通过深度优先的方式生成最终的括号对。这里需要注意的是只有在左括号个数小于n时才可以放置‘(’,左括号个数大于右括号个数时才可以放置‘)’,因此需要分别记下左右括号出现的次数,下面代码中用lCnt和rCnt表示左右括号的个数。这样递归直到长度达到2*n即找到了一个结果。具体代码:
class Solution {
void genParenthesis(vector<string>& rst, string curRst, int lCnt, int rCnt, int n) {
if(curRst.size() == n*2) {
rst.push_back(curRst);
return;
}
else {
if(lCnt < n)
genParenthesis(rst, curRst+"(", lCnt+1, rCnt, n);
if(lCnt > rCnt)
genParenthesis(rst, curRst+")", lCnt, rCnt+1, n);
}
}
public:
vector<string> generateParenthesis(int n) {
vector<string> rst;
genParenthesis(rst, "", 0, 0, n);
return rst;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode DFS