/**
* 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:
*
* "((()))", "(()())", "(())()", "()(())", "()()()"
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void dfs(vector<string> &rs, string str, int left, int right)
{
if (left == 0 && right == 0 )
{
rs.push_back(str);
return;
}
if (left > 0)
{
dfs(rs, str + "(", left - 1, right + 1);
}
if (right > 0)
{
dfs(rs, str+")", left, right-1);
}
}
vector<string> generateParenthesis(int n)
{
vector<string> rs;
dfs(rs, "", n, 0);
return rs;
}
int main()
{
//思路来源Leetcode
vector<string> rs = generateParenthesis(3);
vector<string>::iterator it = rs.begin();
for (; it != rs.end(); it++)
{
cout << *it << endl;
}
system("pause");
return 0;
}
【leetcode】22. Generate Parentheses
最新推荐文章于 2020-10-09 13:50:19 发布