题目要求如下:
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
有符合n*2长度的字串,再判断字串是否合法,合法的字串加入到结果集中。产生所有组合字串,可以使用递归函数,比较简单,所
以只看代码就可以理解了。判断字串是否合法,可以利用栈的方式,如果是')',判断一下栈是否为空,为空则说明不合法,不为空则
弹出栈顶的'('。而遇到‘(’就直接压入栈。这样遍历一次字串,如果栈是空的,则说明字串合法,不为空说明不合法。
这样处理之后,就能AC这道题了。
以下是我的代码,欢迎各位大牛指导交流~
AC,288 ms
//LeetCode_Generate Parentheses
//Written by Zhou
//2014.1.2
class Solution {
public:
//利用栈判断合法字符
bool IsValid(string &str)
{
stack<char> charStack;
for (int i = 0; i < str.length(); ++i)
{
if (str[i] == ')')
{
if (charStack.size() == 0)
return false;
else charStack.pop();
}
else charStack.push(str[i]);
}
if (charStack.size() == 0)
return true;
else return false;
}
//递归函数产生字符组合
void GenParenthesis(char *chars, vector<string> &res, string &temp,int n)
{
if (temp.length() == n) //完成一个组合
{
if (IsValid(temp))
res.push_back(temp);
return;
}
for (int i = 0; i < 2; ++i)
{
temp.push_back(chars[i]);
GenParenthesis(chars,res,temp,n);
temp.pop_back();
}
}
vector<string> generateParenthesis(int n) {
vector<string> res;
if (n <= 0)
return res;
char chars[2] = {'(',')'};
string str("");
GenParenthesis(chars,res,str,n*2);
return res;
}
};