题目链接在此
醉了。easy难度的题刷得差不多了,找了几道medium的开始刷。发现不查下别人怎么写的,就很难下手。哎,修炼不够啊。决定leetcode上medium难度的缓一缓,先看看其他专业书。
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,让你找出所有长度为2n的合法括号串。
代码和思路来自这位大神。里面还有非递归解法。
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> v;
generate(n, n, "", v);
return v;
}
private:
void generate(int leftNum, int rightNum, string s, vector<string> &result) {
if (leftNum == 0 && rightNum == 0) {
result.push_back(s);
}
if (leftNum>0) {
generate(leftNum - 1, rightNum, s + '(', result);
}
if (rightNum>0 && leftNum<rightNum) {
generate(leftNum, rightNum - 1, s + ')', result);
}
}
};