题目:
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、典型的动态规划问题,结束条件是left==n;
2、两个循环条件,每个循环每迭代一次增加一个左括号或者右括号;
代码:
class Solution {
public:
vector<string> generateParenthesis(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
//思路是只要左括号的出现次数小于n,就可以放入左括号,右括号的次数小于左括号时就可以放入右括号
vector<string> res;
if(n>0) generate(n,0,0,"",res);
return res;
}
void generate(int n,int left,int right,string str,vector<string> &res)
{
if(left==n)
{
res.push_back(str.append(n-right,')'));
return;
}
generate(n,left+1,right,str+'(',res);
if(left>right) generate(n,left,right+1,str+')',res);
}
};