原题目
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,表示n对括号,需要我们生成这n对括号组成的、有效的、所有字符串,比如当n=3,需要生成: “((()))”, “(()())”, “(())()”, “()(())”, “()()()”
题解
class Solution {
public:
vector<string> res;
bool check(string str)
{
int left = 0;
// cout << str <<endl;
for(int i =0 ;i < str.size();i++)
{
if(str[i]=='(')
left++;
else if(str[i]==')')
left--;
if(left<0)
return false;
}
return true;
}
void recursive(int left,int right, int n, string curr)
{
if(left>n || right>n) return;
// cout <<left<<" "<<right<<endl;
if(left < n)
{
recursive(left+1,right,n,curr+"(");
recursive(left,right+1,n,curr+")");
}
else if(right <n)
recursive(left,right+1,n,curr+")");
else if(check(curr))
res.push_back(curr);
}
vector<string> generateParenthesis(int n)
{
string curr = "(";
recursive(1,0,n,curr);
return res;
}
};
思路
典型的DFS(回溯)问题,用递归的方式解决,递归函数的输入包括(left,right,n,curr):
- left——当前字符串左括号个数
- right——当前字符串右括号个数
- curr——当前字符串
- n——题目的输入
递归的过程如下:
- 初始化状态:(1,0,n,”(“),因为所有的合法字符串都从左括号开始,最左边的字符不可能是又括号
- 边界条件:当前的left或者right大于n,直接返回
- 递归实现:先判断当前的left是否小于3,如果是的话,递归(left+1,righr,n,curr+”(“)以及(left+1,righr,n,curr+”)”),相当于“下一个元素既可能是左括号又可能是右括号”
- 若left已经等于3,而right<3递归(left+1,righr,n,curr+”)”),意思是“左括号已经用完了,接下来的只可能是右括号”
- 若left等于3且right等于3,则判断这个字符串是否一个合法的括号对,如果合法,就加入到结果中