leetcode22. Generate Parentheses
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
这个问题解的个数为卡特兰数。不过这道题并不是求解的个数,而是将所有合法括号打印出来。
设leftnum和rightnum为左右括号的剩余量,则leftnum>0时可以继续打印"(",当rightnum>leftnum时可以打印")"。
class Solution { public: void generate(int leftnum,int rightnum,string s,vector<string>& res) { if(leftnum==0 && rightnum==0) res.push_back(s); if(leftnum>0) generate(leftnum-1,rightnum,s+"(",res); if(rightnum>leftnum && rightnum>0) generate(leftnum,rightnum-1,s+")",res); } vector<string> generateParenthesis(int n) { vector<string> strs; generate(n,n,"",strs); return strs; } };