问题描述
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:
[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]
解法思路
1)首先是括号的匹配问题,什么是有效的形式,从右括号是否有匹配考虑。设置标志数a=0,从左往右遍历字符串,碰到’(’+1,碰到右括号-1.如果出现小于0的情况,说明无效,最终a==0,这样才能完全匹配正确。
2)回溯法。利用回溯法(DFS)确定所有可能的情况,这里注意一边运行回溯一边运行有效性检测,否则时间代价太大。
C++代码
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
if(n)
{
RecurseDfs(res,"",2*n,0,0);
}
return res;
}
void RecurseDfs(vector<string>&res,string curcombo,int n,int digitsidx,int a)
{
static const char *p="()";
if(a<0) return;
if(n==digitsidx)
{
if(a==0) res.push_back(curcombo);
return;
}
for(const char*letters=p;*letters!='\0';++letters)
{
int b=a;
if(*letters=='(') ++b;//不能直接对a进行操作
else --b;
RecurseDfs(res,curcombo+*letters,n,digitsidx+1,b);
}
}
/*bool Valid(string s)
{
int n=s.size();
if(s[0]!='('||s[n-1]!=')') return false;
int a=0;//记录未匹配的左括号个数
for(int i=0;i<n;++i)
{
if(s[i]=='(') ++a;
else --a;
if(a<0) return false;//左括号不够,肯定错误
}
if(a!=0) return false;//完全匹配
return true;
}*/
};
算法结果
Runtime: 8 ms, faster than 97.94% of C++ online submissions for Generate Parentheses.
Memory Usage: 10 MB, less than 94.13% of C++ online submissions for Generate Parentheses.