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:
[ "((()))", "(()())", "(())()", "()(())", "()()()"]
采用函数递归的方式来实现括号匹配的遍历,注意的是右括号添加的时候左括号要小于右括号的个数才可以。
class Solution { public: void getResult(int left,int right,string s,vector<string> &result) { if(left == 0 &&right == 0) result.push_back(s); if(left>0) getResult(left-1,right,s+'(',result); if(right>0&&left<right) getResult(left,right-1,s+')',result); } vector<string> generateParenthesis(int n) { //因为最后要求括号成对出现,所以右括号添加的时候必须左括号小于右括号才可以 vector<string> result; if(n==0) return result; string s; getResult(n,n,s,result); return result; } };