题目:
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个‘(’和‘)’,生成合法的括号匹配字符串并打印输出
思路:
利用递归方法生成字符串。设置两个变量l和r分别表示剩余左右括号的个数。如果在某次递归时,l>r,说明此时生成的字符串中右括号的个数大于左括号的个数,即会出现')('这样的非法串,所以这种情况直接返回;如果l和r都为0,则说明此时生成的字符串已有3个左括号和3个右括号,且字符串合法,则存入vector容器中后返回;如果以上两种情况都不满足,若此时l大于0,则调用相对应的递归函数,若r大于0,则调用相对应的递归函数,更新参数。
Code:
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> q;
dfs(n,n,"",q);
return q;
}
void dfs(int l, int r, string s, vector<string> &q){
if (l>r) return;
if(!l&&!r) q.push_back(s);
else {
if (l>0) dfs(l-1,r,s+'(',q);
if (r>0) dfs(l,r-1,s+')',q);
}
}
};