您的位置:首页 > 其它

[LeetCode] Generate Parentheses

2013-11-16 17:53 309 查看
Question:

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:

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


Solution:
Use the recursive method. 

class Solution {
public:
void generate_recursively(int l, int r, string s, vector<string> &combination )
{
if (l > 0) generate_recursively(l - 1, r, s + '(', combination);
if (l < r) generate_recursively(l, r - 1, s + ')', combination);
if (r == 0) combination.push_back(s);
}

vector<string> generateParenthesis(int n) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<string> combination;
generate_recursively(n, n, "", combination);
return combination;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息