问题描述: 函数
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.spa
For example, given n = 3, a solution set is:code
"((()))", "(()())", "(())()", "()(())", "()()()"
orm
针对一个长度为2n的合法排列,第1到2n个位置都知足以下规则:左括号的个数大于等于右括号的个数。因此,咱们就能够按照这个规则去打印括号:假设在位置k咱们还剩余left个左括号和right个右括号,若是left>0,则咱们能够直接打印左括号,而不违背规则。可否打印右括号,咱们还必须验证left和right的值是否知足规则,若是left>=right,则咱们不能打印右括号,由于打印会违背合法排列的规则,不然能够打印右括号。若是left和right均为零,则说明咱们已经完成一个合法排列,能够将其打印出来。递归
这个题第一眼看上去就应该使用递归来解决,然而Leetcode给处的函数原形是这样的:
string
class Solution { public: vector<string> generateParenthesis(int n) { } };
我只想说卧槽,在这种状况下把结果做为函数的返回值返回臣妾真心作不到啊!默默地把代码写成了这样:it
void generate(int count1, int count2, string current, int n, vector<string>& combinations) { if (count1 == n && count2 == n) //扫描完了 { combinations.push_back(current); } else { if (count1 < count2) { return; } //打印左括号 if (count1 < n) { generate(count1 + 1, count2, current + "(", n, combinations); } //打印右括号 if (count1 > count2 && count1 <= n) { generate(count1, count2 + 1, current + ")", n, combinations); } } } class Solution { public: vector<string> generateParenthesis(int n) { string current = ""; generate(0, 0, current, n, combinations); return combinations; } vector<string> combinations; };