问题描述:
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.每一个'('都对应一个')',且每个字符串第一个字符必定是'('
2.对于任何一个非空的字符串,若‘(’字符剩余量大于0,则'('可添加进字符串;若')'剩余数大于'(',则')'也可以添加进字符串。以此类推
3.当字符串匹配完时,即'('和')'剩余数目为0
下面是详细的代码:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> v;
getString(v,"",n,n);
return v;
}
void getString(vector<string>& v, string str, int n,int m)
{
if(n == 0 && m == 0)
{
v.push_back(str);
return;
}
if(str == "")
{
getString( v, str + "(", n - 1, m);
}
else
{
if(n > 0)
getString( v, str + "(", n -1 , m);
if(n < m)
getString( v, str + ")", n, m - 1);
}
}
};
有疑问欢迎交流~~