#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
using namespace std;
/*
问题:
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:
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
分析:这是剑指offer的题目应该,记得答案是卡特兰。假设左边的括号为1,右边的括号为0
实际上就是一种递归摆放问题。每一次摆放后检查是否符合要求。
以"(())()"为例,实际上表示"110010",即从任意元素左侧的1的个数>=0的个数
输入:
3
输出:
((())) (()()) (())() ()(()) ()()()
*/
class Solution {
public:
//检验从0到当前摆放位置pos中左括号的个数是否比右括号的个数多
bool isOk(int pos, string& result ,int len)
{
if(result.empty() || pos < 0)
{
return false;
}
int leftCount = 0;
int rightCount = 0;
//这里pos也要取到
for(int i = 0 ; i <= pos ; i++)
{
if('(' == result.at(i))
{
leftCount++;
}
else if(')' == result.at(i))
{
rightCount++;
}
else
{
continue;
}
if(leftCount < rightCount)
{
return false;
}
//如果左边或者右边括号个数大于len/2,也不行
if(leftCount > len/2 || rightCount > len/2)
{
return false;
}
}
return true;
}
//递归生成括号摆放位置:pos表示当前摆放位置
void getParenthesis(int pos , int len , string result, vector<string>& results)
{
//已经生成字符串,直接存储到结果集中
if(pos == len)
{
results.push_back(result);
return;
}
char brackets[2] = {'(' , ')'};
//现在设定0表示左括号,1表示右括号
for(int i = 0 ; i <= 1; i++)
{
result.at(pos) = brackets[i];
//如果摆放是成功的,则直接继续摆放下一个位置
if(isOk(pos , result, len))
{
getParenthesis(pos+1 , len , result , results);
}
}
}
vector<string> generateParenthesis(int n) {
vector<string> results;
//设定一个长度为2*n的字符串
string result(2*n , ' ');//初始化一个长度为2*n的字符串
int pos = 0;
int len = 2 * n;
getParenthesis(pos , len , result, results);
return results;
}
};
void print(vector<string>& results)
{
if(results.empty())
{
cout << "no result" << endl;
return;
}
int size = results.size();
for(int i = 0 ; i < size ; i++)
{
cout << results.at(i) << " ";
}
cout << endl;
}
void process()
{
int n;
Solution solution;
vector<string> results;
while(cin >> n)
{
results = solution.generateParenthesis(n);
print(results);
}
}
int main(int argc , char* argv[])
{
process();
getchar();
return 0;
}
leecode 解题总结:22. Generate Parentheses
最新推荐文章于 2020-10-09 13:50:19 发布