您的位置:首页 > 其它

LeetCode 22: Generate Parentheses

2013-09-01 17:23 471 查看
Difficulty: 3

Frequency: 4

Problem:

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:

class Solution {
public:
vector<string> generateParenthesis(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<string> answer;
if (n<1)
return answer;

vector<char> Parenthesis;
DFS(Parenthesis, answer, n, n);
return answer;
}
void DFS(vector<char> & Parenthesis, vector<string> & answer, int i_left, int i_right)
{
if (i_left==0&&i_right==0)
{
string one_case;
for(int i = 0; i<Parenthesis.size(); i++)
{
one_case += Parenthesis[i];
}
answer.push_back(one_case);
return;
}
if (i_left==i_right)
{
Parenthesis.push_back('(');
DFS(Parenthesis, answer, i_left-1, i_right);
Parenthesis.pop_back();
}
else
{
if (i_left>0)
{
Parenthesis.push_back('(');
DFS(Parenthesis, answer, i_left-1, i_right);
Parenthesis.pop_back();
}
Parenthesis.push_back(')');
DFS(Parenthesis, answer, i_left, i_right-1);
Parenthesis.pop_back();
}
}
};

Notes:

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